![](/img/trans.png)
[英]Using PowerShell to create a function that gets disk serial numbers on an array of computers
[英]Using Powershell to grab disk space info from remote servers and add to array
我一直在嘗試將一些腳本放在一起,以自動執行我們仍在報告的一些手動任務。 這個我試圖哄騙連接到指定的每個遠程服務器(我可以 AD 鏈接並稍后過濾它),提取磁盤信息,進行基本計算,一些格式化,然后將其粘貼在一個數組中以供稍后提取.
我目前遇到錯誤,指出我正在“嘗試除以 0”,並且我的數組不返回任何數據(我假設是因為上述原因)。必須有一些小東西我丟失了。好吧,希望很小。這是我到達的地方:
#Variable listing servers to check. Can convert to a csv, or direct connection to AD
using OU's.
$ServersToScan = @('x, y, z')
#Blank Array for Report
$finalReport = @()
#Threshold Definition %
$Critical = 5
$Warning = 15
#Action for each server
foreach ($i in $ServersToScan)
{
Enter-PSSession -ComputerName $i
#Fixed Disk Info Gather
$diskObj = Get-CimInstance -ClassName Win32_LogicalDisk | Where-Object { $_.DriveType -eq 3 }
#Iterate each disk information - rewrite as foreach ($x in $diskObj) - rewritten 3/31/22
foreach ($diskObj in $diskObj)
{
# Calculate the free space percentage
$percentFree = [int](($_.FreeSpace / $_.Size) * 100)
# Determine the "Status"
if ($percentFree -gt $Warning) {
$Status = 'Normal'
}
elseif ($percentFree -gt $Critical) {
$Status = 'Warning'
}
elseif ($percentFree -le $Critical) {
$Status = 'Critical'
}
# Compose the properties of the object to add to the report
$tempObj = [ordered]@{
'Computer Name' = $i
'Drive Letter' = $_.DeviceID
'Drive Name' = $_.VolumeName
'Total Space (GB)' = [int]($_.Size / 1gb)
'Free Space (GB)' = [int]($_.FreeSpace / 1gb)
'Free Space (%)' = "{0}{1}" -f [int]$percentFree, '%'
'Status' = $Status
}
# Add the object to the final report
$finalReport += New-Object psobject -property $tempObj
}
Exit-PSSession
}
return $finalReport
任何見解都會很棒 - 非常感謝!
有兩個主要問題,第一個,正如Jeff Zeitlin指出的那樣, 自動變量$_
( $PSItem
)在foreach
循環中沒有效果,它實際上是$null
:
[int](($null / $null) * 100)
# => RuntimeException: Attempted to divide by zero.
第二個問題是您使用Enter-PSSession
,它專門用於交互式會話。 對於無人參與的腳本,您可以改用Invoke-Command
,但是,在這種情況下,我們還可以依賴Get-CimInstance -ComputerName
來查詢遠程計算機(請注意,此操作是並行執行的,不需要循環遍歷$serversToScan
數組)。
$ServersToScan = 'x, y, z'
#Threshold Definition %
$Critical = 0.5
$Warning = 0.15
$params = @{
ClassName = 'Win32_LogicalDisk'
Filter = "DriveType = '3'"
ComputerName = $ServersToScan
}
$finalReport = Get-CimInstance @params | ForEach-Object {
$free = $_.FreeSpace / $_.Size
$status = switch($free) {
{ $_ -gt $Warning } { 'Normal'; break }
{ $_ -gt $Critical } { 'Warning'; break }
Default { 'Critical' }
}
[pscustomobject]@{
'Computer Name' = $_.PSComputerName
'Drive Letter' = $_.DeviceID
'Drive Name' = $_.VolumeName
'Total Space (GB)' = $_.Size / 1Gb
'Free Space (GB)' = $_.FreeSpace / 1Gb
'Free Space (%)' = $free.ToString('P0')
'Status' = $status
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.