2

由于我需要超时参数,我正在尝试使用 Daniele 的自定义get-wmiobject 函数从远程计算机检索逻辑磁盘信息。

该函数工作得很好,但我还想将 $results 存储在一个变量中并循环通过它来查找可用空间已降至某个阈值以下的驱动器。

这是我的部分代码。我在 Daniele 的函数中添加了一个 $where 参数以附加到查询中。他的功能在其他方面是相同的。

Function get-wmicustom([string]$computername,[string]$namespace,[string]$class,[int]$timeout=15,[string]$where)
{
    $ConnectionOptions = new-object System.Management.ConnectionOptions
    $EnumerationOptions = new-object System.Management.EnumerationOptions

    $timeoutseconds = new-timespan -seconds $timeout
    $EnumerationOptions.set_timeout($timeoutseconds)

    $assembledpath = "\\" + $computername + "\" + $namespace
    write-host $assembledpath -foregroundcolor green

    $Scope = new-object System.Management.ManagementScope $assembledpath, $ConnectionOptions
    $Scope.Connect()

    $querystring = "SELECT * FROM " + $class + " " + $where
    write-host $querystring

    $query = new-object System.Management.ObjectQuery $querystring
    $searcher = new-object System.Management.ManagementObjectSearcher
    $searcher.set_options($EnumerationOptions)
    $searcher.Query = $querystring
    $searcher.Scope = $Scope

    trap { $_ } $result = $searcher.Get()

    return $result
}

$servers = get-content -Path "c:\ServerMonitoring\servers.txt"
$threshold = 5

foreach($server in $servers)
{
    write-host "Checking server $server..."

    #$drive_information = get-wmiobject -ComputerName $server -query "select Name, FreeSpace from Win32_logicaldisk where MediaType = 12"
    $drive_information = get-wmicustom -ComputerName $server -NameSpace "root\cimv2" -Class Win32_logicaldisk -TimeOut 3 -Where "WHERE MediaType = 12"

    write-host "Drive information collected from $server..."

    foreach($drive in $drive_information)
    {
        $drive_freespace_gb = [Math]::Round($drive.FreeSpace / 1024 / 1024 / 1024, 2)
        $drive_name = $drive.Name

        write-host "Checking drive $drive_name"

        if ($drive_freespace_gb -le $threshold -and $drive_name -notlike "*T:*")
        {
            write-host "Drive $drive_name on $server has only $drive_freespace_gb GB left."
            $wait = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
        }
    }
}

当我从命令行运行这个脚本时,它给出了这个错误:

“=”运算符失败:类无效。

我知道这可能是由于这里返回的 $results 是一个 ManagementObjectCollection .Net 对象。所以我尝试通过将 ToString() 方法附加到 Get() 方法来将其转换为字符串。这停止了​​错误,但 ToString() 方法只返回对象所属类的名称,而不是实际数据。我也尝试过 Get().GetEnumerator().ToString() 得到类似的结果。

如何将结果转换为 Powershell 可读的格式?

4

1 回答 1

0

语法可以是:

$SearchKBsResult | select <property you want> | foreach {$_.property you want}
于 2015-06-01T15:58:36.930 回答