避免多次WMI调用同一台计算机?

时间:2017-03-22 13:27:47

标签: powershell wmi

我在使用Powershell的许多远程计算机上查询WMI类。

我有以下功能非常好但是因为对远程计算机做任何事情需要一些时间而且我希望尽量减少这一点:

$file = Get-Content c:\temp\bitlocker\non-compliant-wksn1.txt
foreach ($ComputerName in $file) {
    if (Test-Connection -ComputerName $ComputerName -Quiet) {
        $Hostname = (Get-WmiObject -Class Win32_ComputerSystem -ComputerName $ComputerName).Name
        $model = (Get-WmiObject -Class Win32_ComputerSystem -ComputerName $ComputerName).Model
        $OS = (Get-WmiObject -Class Win32_OperatingSystem -ComputerName $ComputerName).Version
        $TpmActivate = (Get-WMIObject -Namespace "root/CIMV2/Security/MicrosoftTpm" -query "SELECT * FROM Win32_TPM" -ComputerName $ComputerName).IsActivated_InitialValue
        $TpmEnabled = (Get-WMIObject -Namespace "root/CIMV2/Security/MicrosoftTpm" -query "SELECT * FROM Win32_TPM" -ComputerName $ComputerName).IsEnabled_InitialValue
        $TpmOwned = (Get-WMIObject -Namespace "root/CIMV2/Security/MicrosoftTpm" -query "SELECT * FROM Win32_TPM" -ComputerName $ComputerName).IsOwned_InitialValue
        $Encrypted = (Get-WMIObject -Namespace "root/CIMV2/Security/MicrosoftVolumeEncryption" -query "SELECT * FROM Win32_EncryptableVolume WHERE DriveLetter='C:'" -ComputerName $ComputerName).ProtectionStatus
        write-host $ComputerName "`t" $Hostname "`t" $model "`t" $OS "`t" $TpmActivate "`t" $TpmEnabled "`t" $TpmOwned "`t" "C:" "`t" $Encrypted
        }
    else {
        write-host $Computername "`t" "Offline"
    }
}

从代码中可以看出,我正在进行2次远程调用,从Win32_ComputerSystem获取2个值,3次远程调用从Win32_TPM获取3个值。是否有可能采取这5个远程调用,并以某种方式将它们减少为2个远程调用(每个类一个),它返回我需要的所有信息并将它们存储在我的变量中(希望能加快速度)?

TIA

1 个答案:

答案 0 :(得分:1)

正如您所注意到的,这些呼叫中的每一个都进行远程呼叫:

$Hostname = (Get-WmiObject -Class Win32_ComputerSystem -ComputerName $ComputerName).Name
$model = (Get-WmiObject -Class Win32_ComputerSystem -ComputerName $ComputerName).Model
$OS = (Get-WmiObject -Class Win32_OperatingSystem -ComputerName $ComputerName).Version**strong text**

而是在一次调用中获取完整的WMI对象,然后提取所需的属性:

$c = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $ComputerName
$Hostname = $c.Name
$model = $c.Model
$OS = $c.Version

更好的是,只从该对象获取所需的属性:

$c = Get-WmiObject -Query 'select Name, Model, Version from Win32_ComputerSystem' -ComputerName $ComputerName
$Hostname = $c.Name
$model = $c.Model
$OS = $c.Version