如何将ManagementObjectCollection对象转换为Powershell可读的格式?

时间:2013-04-03 00:30:38

标签: .net powershell wmi-query

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

该函数完全正常,但我还想将$ 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可读的格式?

1 个答案:

答案 0 :(得分:0)

语法可以是:

$SearchKBsResult | select <property you want> | foreach {$_.property you want}