由于计算机上的wmi配置_VBScript WMI教程:从多台计算机检索C驱动器上的可用空间

由于计算机上的wmi配置

介绍 (Introduction)

在我作为Experts Exchange的VBScript贡献者参与期间,我遇到的最常见问题之一是:
"I have a script that runs against only one computer. How can I make it run against a list of computers in a text file?"
This article will provide you with an understanding of what you need to do to get this done, and also throw in some helpful features to make things a bit "neater".
“我有一个只能在一台计算机上运行的脚本。如何使其在文本文件中的计算机列表上运行?”
本文将使您了解完成此操作所需执行的操作,并提供一些有用的功能以使事情“更整洁”。

我们从哪里开始? (Where Do We Start?)

我们应该从出现问题的脚本开始; 一台只能在一台计算机上运行。 这是一个简单的脚本,它将检索本地计算机C驱动器上的可用空间。 可用空间信息是使用WMI,Windows Management Instrumentation收集的。 WMI提供对许多类的访问,这些类存储有关系统及其设置和状态的信息。
strComputer = "."
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("SELECT FreeSpace FROM Win32_LogicalDisk WHERE DeviceID = 'C:'")
For Each objItem In colItems
   dblFreeSpace = Round(objItem.FreeSpace / 1024 / 1024, 3)
Next
WScript.Echo dblFreeSpace & " MB Free"

There's not much to this script, but here’s how it works.

该脚本没有太多内容,但是它的工作原理如下。

strComputer = "." refers to the local computer, so the WMI connection will be made to the computer that the script is running on.

strComputer =“。” 是指本地计算机,因此将与运行脚本的计算机建立WMI连接。

objWMIService is the user defined variable name that represents the WMI Connection we are creating.  We can then use that connection to execute the WMI queries we need to use.

objWMIService是用户定义的变量名,代表我们正在创建的WMI连接。 然后,我们可以使用该连接来执行我们需要使用的WMI查询。

The GetObject call is the method that actually creates the WMI connection, and winmgmts represents the WMI Service.

调用GetObject是实际创建WMI连接的方法, winmgmts代表WMI服务。

{impersonationLevel=impersonate} is the default security moniker, which doesn't need to be specified, but I like to keep it in, just for completeness.

{impersonationLevel = impers onate}是默认的安全绰号,无需指定,但我想保留它,只是为了完整性。

Finally, \root\cimv2 is the WMI namespace that we are connecting to, which is the most common Namespace to use.

最后, \ root \ cimv2是我们要连接的WMI命名空间,这是最常用的命名空间。

Now to the working part of the script. ExecQuery is the method that allows us to execute a WMI query that retrieves a collection of objects for us to enumerate.  In this case, as we are only interested in the FreeSpace property, we just select FreeSpace from the Win32_LogicalDisk class.  If you want to know all of the properties that are available, you can do either of the following:

现在到脚本的工作部分。 ExecQuery是一种使我们能够执行WMI查询的方法,该查询检索对象的集合供我们枚举。 在这种情况下,由于我们只对FreeSpace属性感兴趣,因此只需从Win32_LogicalDisk类中选择FreeSpace 。 如果您想知道所有可用的属性,则可以执行以下任一操作:

Download the ScriptoMaticV2.hta tool from Microsoft, and select the appropriate namespace, then select the appropriate class.  All of the properties will be displayed to you in the code window.

从Microsoft下载ScriptoMaticV2.hta工具,并选择适当的名称空间,然后选择适当的类。 所有属性将在代码窗口中显示给您。

View the class documentation on the MSDN website.  Simply search for the class name, and you will find the full documentation for that class.

在MSDN网站上查看类文档。 只需搜索类名称,即可找到该类的完整文档。

The query is written in Windows Query Language (WQL), so while the syntax is similar to SQL, it does not support all of the features of SQL.  For the purposes of this script, we are able to further restrict the results of the query to only a logical disk with a DeviceID of "C:".

该查询是用Windows查询语言(WQL)编写的,因此尽管语法类似于SQL,但它不支持SQL的所有功能。 就此脚本而言,我们可以进一步将查询结果限制为DeviceID为“ C:”的逻辑磁盘。

Now, how do we enumerate the objects returned by the WMI query?  Using a For Each … Next loop.  In our loop, objItem refers to each individual element of colItems as we step through.  To refer to the property of each item we are interested in, we use objItem.FreeSpace, and store that value in dblFreeSpace.  Notice we are performing a calculation on this value.  This is because the FreeSpace property returns a value in bytes, and we want it in megabytes, so we divide it by 1024, then by 1024 again.  We have also used the Round function, to round the calculated figure to three decimal places.

现在,我们如何枚举WMI查询返回的对象? 使用For Each…Next循环。 在我们的循环中, objItem我们逐步执行的colItems的每个单独元素。 要引用我们感兴趣的每个项目的属性,我们使用objItem.FreeSpace ,并将该值存储在dblFreeSpace中 。 注意,我们正在对此值进行计算。 这是因为FreeSpace属性返回的值以字节为单位,而我们希望以兆字节为单位,因此我们将其除以1024,然后再除以1024。 我们还使用了Round函数,将计算出的数字四舍五入到小数点后三位。

Finally, once we have that value, and the loop exits, we echo the result to the screen, using WScript.Echo, and append the " MB Free" string, just to make the output nicer.

最后,一旦有了该值,然后退出循环,就可以使用WScript.Echo将结果回显到屏幕上,并附加“ MB Free”字符串,以使输出更好。

对,那么现在多台计算机呢? (Right, So Now What About Multiple Computers?)

好的,在不进行介绍的情况下,我们现在需要针对多台计算机进行这项工作。 为了进行此练习,我们将从纯文本文件获取输入,该文件由每行一个计算机名组成,如下所示:
Computer1
Computer2
Computer3

Having done that, assuming the file name is computers.txt, here's the code that will read this file, and obtain the free space on C Drive of each computer, and output it to a CSV file.

完成此操作后,假设文件名为computers.txt,下面的代码将读取该文件,并获取每台计算机的C驱动器上的可用空间,并将其输出到CSV文件。

strInputFile = "computers.txt"
strOutputFile = "CDriveSpace.csv"

Set objFSO = CreateObject("Scripting.FileSystemObject")
Const intForReading = 1
Const WMITimeOutInSeconds = 10
Const wbemFlagReturnImmediately = &h10
Const wbemFlagForwardOnly = &h20

Set objInputFile = objFSO.OpenTextFile(strInputFile, intForReading, False)
Set objOutputFile = objFSO.CreateTextFile(strOutputFile, True)
objOutputFile.WriteLine """Computer"",""C Drive Free Space (MB)"""

While Not objInputFile.AtEndOfStream
   strComputer = objInputFile.ReadLine
   If Ping(strComputer) = True Then
      strReturn = TestWMIConnection(strComputer, WMITimeOutInSeconds)

      If strReturn = "success" Then

         Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
         ' The wbemFlagReturnImmediately flag is the default ExecQuery behavior and is semi-synchronous. The important optimization is the addition of the wbemFlagForwardOnly flag.
         ' Combining wbemFlagReturnImmediately with wbemFlagForwardOnly results in a forward-only enumerator. A forward-only enumerator performs much faster than the default enumerator,
         ' because WMI doesn't maintain references to objects in the SWbemObjectSet.
         ' Source: http://msdn.microsoft.com/en-us/library/ms974547.aspx
         Set colItems = objWMIService.ExecQuery("SELECT FreeSpace FROM Win32_LogicalDisk WHERE DeviceID = 'C:'", "WQL", wbemFlagReturnImmediately + wbemFlagForwardOnly)
         For Each objItem In colItems
            dblFreeSpace = Round(objItem.FreeSpace / 1024 / 1024, 3)
         Next
         objOutputFile.WriteLine """" & strComputer & """,""" & dblFreeSpace & """"

      ElseIf strReturn = "failed" Then
         objOutputFile.WriteLine """" & strComputer & """,""WMI ERROR"""

      Else
         objOutputFile.WriteLine """" & strComputer & """,""WMI TIME OUT"""

      End If

   Else
      objOutputFile.WriteLine """" & strComputer & """,""OFFLINE"""

   End If
Wend

objInputFile.Close
objOutputFile.Close
WScript.Echo "Script complete. Please see " & strOutputFile

Function Ping(strComputer)
   Dim objShell, boolCode
   Set objShell = CreateObject("WScript.Shell")
   boolCode = objShell.Run("Ping -n 1 -w 300 " & strComputer, 0, True)
   If boolCode = 0 Then
      Ping = True
   Else
      Ping = False
   End If
End Function

Function TestWMIConnection(strComputer, intTimeOutInSeconds)
   ' Function written by Rob Sampson - 12 Jan 2011
   ' Experts-Exchange volunteer: http://www.experts-exchange.com/M_3820065.html
   ' Return strings from this function are in lower case, and consist of:
   ' "success": WMI Connection successful
   ' "failed": WMI Connection failed
   ' "time out": WMI Connection attempt timed out

   Set objFSO = CreateObject("Scripting.FileSystemObject")
   strTempScript = Replace(WScript.ScriptFullName, WScript.ScriptName, "") & "TempWMITestToBeDeleted.vbs"

   Set objTempFile = objFSO.CreateTextFile(strTempScript, True)
   objTempFile.WriteLine "On Error Resume Next"
   objTempFile.WriteLine "Set objWMIService = GetObject(""winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2"")"
   objTempFile.WriteLine "If Err.Number = 0 Then"
   objTempFile.WriteLine vbTab & "WScript.StdOut.Write ""success"""
   objTempFile.WriteLine "Else"
   objTempFile.WriteLine vbTab & "WScript.StdOut.Write ""failed"""
   objTempFile.WriteLine "End If"
   objTempFile.Close

   Set objShell = CreateObject("WScript.Shell")
   Set objExec = objShell.Exec("wscript " & objFSO.GetFile(strTempScript).ShortPath)
   intSeconds = 0
   While objExec.Status = 0 And intSeconds <= intTimeOutInSeconds
      WScript.Sleep 1000
      intSeconds = intSeconds + 1
   Wend
   If objExec.Status = 1 Then
      strReturn = objExec.StdOut.ReadAll
   Else
      On Error Resume Next
      objExec.Terminate
      Err.Clear
      On Error GoTo 0
      strReturn = "time out"
   End If
   objFSO.DeleteFile strTempScript, True

   TestWMIConnection = LCase(strReturn)
End Function

这是如何运作的? (How Does THAT Work?)

我知道,这看起来有些令人生畏,但这里也有一些额外的功能和错误检查,我将在后面进行解释。

The only variable values we have in this script, for the user to configure, are these two:

我们可以在此脚本中为用户配置的唯一变量值为以下两个:

strInputFile = "computers.txt"
strOutputFile = "CDriveSpace.csv"

The first is the name of the input file to read from, and the second is the name of the output file for the script to create.  If a full path is not specified, the files will be created in the same directory that the script is running from (i.e., the current directory).

第一个是要读取的输入文件的名称,第二个是要创建的脚本的输出文件的名称。 如果未指定完整路径,则将在脚本运行所在的目录(即当前目录)中创建文件。

The first thing we need to do, when we know we’re going to work with the file system, is create an instance of the Scripting.FileSystemObject object.  This is the ActiveX object that allows us to use basic file system functions. That is provided by this line:

当我们知道要使用文件系统时,要做的第一件事就是创建Scripting.FileSystemObject的实例。 目的。 这是ActiveX对象,它使我们可以使用基本文件系统功能。 这是此行提供的:

Set objFSO = CreateObject("Scripting.FileSystemObject")
Const intForReading = 1
Const WMITimeOutInSeconds = 10
Const wbemFlagReturnImmediately = &h10
Const wbemFlagForwardOnly = &h20

The first is for use when opening text files using the OpenTextFile method.  WMITimeOutInSeconds is a constant for use with the custom function I have written: TestWMIConnection.  The last two are for use as extra parameters (see the comments in the code for their explanation) for the ExecQuery method we touched on earlier.

第一种是在使用OpenTextFile方法打开文本文件时使用的。 WMITimeOutInSeconds是一个常量,可与我编写的自定义函数TestWMIConnection一起使用 。 最后两个用作我们前面提到的ExecQuery方法的额外参数(请参阅代码中的注释以获取解释)。

The OpenTextFile method returns a text stream object we can use to read through the input file we have instructed it to open.  Its first parameter is for the file path of the file to open, the second parameter is the operation mode, and the third is the create file flag, specifying whether or not to create the file if it doesn’t already exist.  For the operation mode, we have specified intForReading (which evaluates to 1), meaning the file is opened in read mode only.  Other options are write mode (integer value of 2), or append mode (integer value of 8).  We could have defined those constants, in case we needed them, but I have opted not to (because we don’t need them).  There is a fourth parameter to the OpenTextFile method, for the file format, being ASCII or Unicode, but I have not used that. The default format uses the system default.

OpenTextFile方法返回一个文本流对象,我们可以使用它来通读我们指示打开的输入文件。 它的第一个参数是打开文件的文件路径,第二个参数是操作模式,第三个参数是创建文件标志,用于指定是否创建文件(如果尚不存在)。 对于操作模式,我们指定了intForReading (其值为1),这意味着该文件仅在读取模式下打开。 其他选项是写入模式(整数值2)或追加模式(整数值8)。 我们可以定义这些常量,以防万一我们需要它们,但是我选择了不这样做(因为我们不需要它们)。 对于文件格式, OpenTextFile方法有第四个参数,是ASCII或Unicode,但我没有使用过。 默认格式使用系统默认值。

The CreateTextFile method returns a text stream object we can use to write information to, writing to the file that we have instructed it to create.  The second parameter specifies whether to overwrite an existing file or not.  We have specified True so that it overwrites the report each time the script is run.  There is a third parameter to the CreateTextFile method, for the file format, being ASCII or Unicode, but I have not used that. The default format uses the system default.

CreateTextFile方法返回一个文本流对象,可用于向其写入信息,并写入已指示其创建的文件。 第二个参数指定是否覆盖现有文件。 我们已指定True,以便每次运行脚本时都会覆盖报告。 对于文件格式, CreateTextFile方法有第三个参数,是ASCII或Unicode,但我没有使用过。 默认格式使用系统默认值。

Now that we have created our file objects, we can begin to read and write to them.  First off, we’ll write a header line to our CSV file, by using this:

现在我们已经创建了文件对象,我们可以开始对其进行读写了。 首先,我们将使用以下代码将标题行写入CSV文件:

objOutputFile.WriteLine """Computer"",""C Drive Free Space (MB)"""

To begin reading through the Input file, you need to use a loop.  I tend to use a While loop, while others like to use a Do loop.  They both do the same thing, it’s just personal preference.  This is the block responsible for reading through the input file:

要开始阅读Input文件,您需要使用循环。 我倾向于使用While循环,而其他人则喜欢使用Do循环。 他们俩都做同一件事,这只是个人喜好。 这是负责读取输入文件的块:

While Not objInputFile.AtEndOfStream
   strComputer = objInputFile.ReadLine
   ...
Wend

The ReadLine method reads one line at a time, and returns it to the variable strComputer.  The While loop will continue to check for the AtEndOfStream condition, reading one line at a time, until the end of the file is reached.

ReadLine方法一次读取一行,然后将其返回到变量strComputerWhile循环将继续检查AtEndOfStream条件,一次读取一行,直到到达文件末尾。

So on each iteration through the loop, we can work with one computer name from the text file at a time.  The next few lines:

因此,在循环的每次迭代中,我们可以一次使用文本文件中的一个计算机名称。 接下来的几行:

   If Ping(strComputer) = True Then
      strReturn = TestWMIConnection(strComputer, WMITimeOutInSeconds)
      If strReturn = "success" Then

Perform some connectivity checks, which I’ll explain later. For now, assume each computer passes the connectivity checks.  Once that occurs, we end up where we were before, creating the WMI connection, and reading the required values from the current computer we are querying.  This time, however, instead of outputting the result to the screen, we write it to the CSV file, using:

执行一些连接检查,我将在后面解释。 现在,假设每台计算机都通过了连接检查。 一旦发生这种情况,我们就可以回到以前的状态,创建WMI连接,并从正在查询的当前计算机中读取所需的值。 但是,这一次,我们没有将结果输出到屏幕,而是使用以下方法将其写入CSV文件:

         objOutputFile.WriteLine """" & strComputer & """,""" & dblFreeSpace & """"

This writes the computer name (enclosed in quotes) in the first field, and the free space value (enclosed in quotes) in the second field.  Note this time, though, we have not added the " MB Free" string, because this is already implied by the header we have written.

这将在第一个字段中写入计算机名称(用引号引起来),在第二个字段中写入可用空间值(用引号引起来)。 但是请注意,这次,我们没有添加“ MB Free”字符串,因为我们编写的标头已经暗示了这一点。

Finally, aside from the other Else conditions for my connectivity tests, we exit the loop, close the two files, and display a message to the user that the script has finished.

最后,除了我的连通性测试的其他条件, 否则 ,我们退出循环,关闭这两个文件,并显示一条消息给用户脚本已经完成。

objInputFile.Close
objOutputFile.Close
WScript.Echo "Script complete. Please see " & strOutputFile

大! 那么多余的东西呢? (Great! So What About The Extra Stuff?)

在此脚本中,我提供了两个自定义函数:
Function Ping(strComputer)
   ...
End Function
Function TestWMIConnection(strComputer, intTimeOutInSeconds)
   ...
End Function

We call these using the following lines:

我们使用以下几行来调用它们:

   If Ping(strComputer) = True Then
      strReturn = TestWMIConnection(strComputer, WMITimeOutInSeconds)

The call to the Ping function returns True or False based on the response from the command:

对Ping函数的调用根据以下命令的响应返回TrueFalse

Ping -n 1 -w 300 computername

That’s a shell command, so we need to execute it using the Run method of the WScript.Shell object.  We instantiate the WScript.Shell object using:

那是一个shell命令,因此我们需要使用WScript.Shell对象的Run方法执行它。 我们使用以下方法实例化WScript.Shell对象:

   Set objShell = CreateObject("WScript.Shell")

And execute the command using:

并使用以下命令执行命令:

   boolCode = objShell.Run("Ping -n 1 -w 300 " & strComputer, 0, True)

The ping command returns 0 if successful, or 1 if it fails.  Therefore, we can get the Ping function to return True or False to the main code, so we know whether a computer is online or not.

如果成功,则ping命令将返回0,否则将返回1。 因此,我们可以获取Ping函数以将TrueFalse返回到主代码,以便我们知道计算机是否在线。

I wrote the TestWMIConnection function in response to many people asking whether WMI supported a time out, because sometimes the connection would hang for a long period of time before finally returning a connection error, or sometimes hang indefinitely.  There is a method you can employ that allows a two minute time out, which consists of the following code:

我写了TestWMIConnection函数来回答许多人询问WMI是否支持超时的问题,因为有时连接会挂起很长一段时间,最后才返回连接错误,或者有时会无限期挂起。 您可以采用一种允许两分钟超时的方法,该方法由以下代码组成:

Const wbemConnectFlagUseMaxWait = 128
Set objSWBemLocator = CreateObject("WbemScripting.SWbemLocator")
Set objWMIService = objSWBemLocator.ConnectServer(strComputer, "root\cimv2", Null, Null, , ,wbemConnectFlagUseMaxWait)
Set colItems = objWMIService.ExecQuery("SELECT FreeSpace FROM Win32_LogicalDisk WHERE DeviceID = 'C:'")

However, I found that sometimes that didn’t work, and I also didn’t want to wait 2 minutes per machine, because when you’re querying a few hundred, or even thousand, machines this can take far too long.

但是,我发现有时不起作用,我也不想每台计算机等待2分钟,因为当您查询几百甚至上千台计算机时,这可能会花费太长时间。

The hurdle we need to get over with the time out of the GetObject call is that it is a synchronous method, meaning that the script waits for the current command to finish executing before continuing with the next command.  To get over this, I make the function write another, temporary script, and execute it, being able to either wait for that second script to complete (returning a connection result), or force it to terminate if the timeout value has been reached.

我们需要克服GetObject调用超时的障碍是,它是一个同步方法,这意味着脚本在继续下一个命令之前等待当前命令完成执行。 为了解决这个问题,我使该函数编写另一个临时脚本并执行它,可以等待第二个脚本完成(返回连接结果),或者如果达到超时值则强制其终止。

The temporary script is created by using a series of WriteLine statements, but this time, we write actual lines of code.  Once the temporary script is written, this is what the contents of that file looks like:

临时脚本是通过使用一系列WriteLine语句创建的,但是这次,我们编写实际的代码行。 写入临时脚本后,该文件的内容将如下所示:

On Error Resume Next
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\<computername>\root\cimv2")
If Err.Number = 0 Then
   WScript.StdOut.Write "success"
Else
   WScript.StdOut.Write "failed"
End If

Except that <computername> is actually written into the script as the actual computer name that we are checking from the main code.  So, what this second script does, that we can monitor asynchronously, is perform the same GetObject call that we’ve already used, and returns "success" or "failed" depending on whether there was an error or not.  The advantage to writing out a second script, and executing it, is that we can enforce a time out, which is the purpose of this function.

除了<computername>实际上是作为我们要从主代码检查的实际计算机名称写入脚本中之外。 因此,我们可以异步监视的第二个脚本所做的是,执行我们已经使用的同一GetObject调用,并根据是否存在错误返回“成功”或“失败”。 编写并执行第二个脚本的好处是我们可以强制执行超时,这是此功能的目的。

To be able to terminate the second script, we use the Exec method of the WScript.Shell object.  Whereas the Run method is synchronous, the Exec method is asynchronous, so you can monitor its status to see whether it has completed or not, using a loop.  During that loop, we use WScript.Sleep 1000 to pause the script for 1000 milliseconds (1 second) on each iteration, and increase a counter by one.  We do this until either the script is complete, or the time out value has been reached, based on comparing the counter with the time out value that was passed to the function.  In this script, I have passed a time out value of 10 seconds.  Once we know that the script has ended, we can read back the result using:

为了能够终止第二个脚本,我们使用WScript.Shell对象的Exec方法。 尽管Run方法是同步的,而Exec方法却是异步的,所以您可以使用循环来监视其状态以查看其是否已完成。 在该循环中,我们使用WScript.Sleep 1000在每次迭代中将脚本暂停1000毫秒(1秒),然后将计数器增加1。 我们根据计数器与传递给函数的超时值进行比较,直到脚本完成或达到超时值为止。 在此脚本中,我传递了10秒的超时值。 一旦知道脚本已结束,就可以使用以下命令回读结果:

strReturn = objExec.StdOut.ReadAll

The temporary script returns either "success" or "failed" to the TestWMIConnection function, and the function then passes that, or "time out", back to the main code.  The temporary script is deleted just before the function exits.

临时脚本将“成功”或“失败”返回给TestWMIConnection函数,然后该函数将其或“超时”传递回主代码。 在函数退出之前,临时脚本将被删除。

The output for the connectivity tests:

连接测试的输出:

      objOutputFile.WriteLine """" & strComputer & """,""WMI ERROR"""
      objOutputFile.WriteLine """" & strComputer & """,""WMI TIME OUT"""
      objOutputFile.WriteLine """" & strComputer & """,""OFFLINE"""

Each write "WMI ERROR", "WMI TIME OUT", or "OFFLINE" respectively, in the second field of the CSV file, depending on which condition was triggered.

根据触发的条件,分别在CSV文件的第二个字段中分别写入“ WMI ERROR”,“ WMI TIME OUT”或“ OFFLINE”。

结论 (Conclusion)

So there you have it.  A script that reads computer names from a text file, tests the ping and WMI connectivity to each machine, queries WMI to retrieve the free space on C Drive, and writes the output to a CSV file.

所以你有它。 该脚本从文本文件读取计算机名称,测试ping和WMI与每台计算机的连接,查询WMI以检索C驱动器上的可用空间,并将输出写入CSV文件。

My apologies for this article being much longer than I intended, but I wanted to include the extra bits and pieces, to provide a complete script, and also give you an understanding of some particular checks that need to be implemented when using a script like this in a large environment.  Without such tests, you either receive errors, your script terminates unexpectedly, or it takes days to complete.

我为这篇文章道歉的时间比我预期的要长得多,但是我想包括一些额外的内容,以提供完整的脚本,并让您了解使用此类脚本时需要实施的一些特定检查在大环境中。 如果不进行此类测试,则您可能会收到错误消息,脚本意外终止或需要几天的时间才能完成。

On a final note, there is another version of the Ping function that uses WMI itself (only locally though), which is supported in Windows XP or greater.  I still use the shell command though, because I’ve been using that since Windows 2000, and just haven’t changed.

最后一点,还有Ping函数的另一个版本,它使用WMI本身(尽管仅在本地),Windows XP或更高版本支持该功能。 不过,我仍然使用shell命令,因为自Windows 2000以来我就一直在使用它,并且没有改变。

Function Ping(strComputer)
   Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
   Set colPings = objWMIService.ExecQuery ("Select StatusCode From Win32_PingStatus Where Address = '" & strComputer & "'")
   For Each objStatus in colPings
      If IsNull(objStatus.StatusCode) or objStatus.StatusCode <> 0 Then 
         Ping = False
      Else
         Ping = True
      End If
   Next
End Function

翻译自: https://www.experts-exchange.com/articles/4379/VBScript-WMI-Tutorial-Retrieve-Free-Space-On-C-Drive-From-Multiple-Computers.html

由于计算机上的wmi配置

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值