gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 00:19:47 25 4
gpt4 key购买 nike

由于需要超时参数,我试图使用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")
}
}
}

当我从命令行运行此脚本时,会出现以下错误:

The '=' operator failed: Invalid Class.



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

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

最佳答案

语法可以是:

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

关于.net - 如何将ManagementObjectCollection对象转换为Powershell可读的格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15776896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com