大部分代碼是從在線博客中提取的,但我認為這正是我需要解決的方法。我想根據正常運行時間從 OU 中獲取前 4 臺機器,并運行位于前 4 臺機器中的每臺機器上的腳本。我知道問題涉及 Array 無法訪問 Get-ADComputer 屬性,但我不確定如何將這些新屬性傳遞回它們的原始物件。這按預期作業,直到最后進入 foreach 回圈。
$scriptBlock={
$wmi = Get-WmiObject -Class Win32_OperatingSystem
($wmi.ConvertToDateTime($wmi.LocalDateTime) – $wmi.ConvertToDateTime($wmi.LastBootUpTime)).TotalHours
}
$UpTime = @()
Get-ADComputer -Filter 'ObjectClass -eq "Computer"' -SearchBase "OU=***,OU=***,OU=***,DC=***,DC=***" -SearchScope Subtree `
| ForEach-Object { $Uptime = `
(New-Object psobject -Property @{
"ComputerName" = $_.DNSHostName
"UpTimeHours" = (Invoke-Command -ComputerName $_.DNSHostName -ScriptBlock $scriptBlock)
}
)
}
$UpTime | Where-Object {$_.UpTimeHours -ne ""} | sort-object -property @{Expression="UpTimeHours";Descending=$true} | `
Select-Object -Property ComputerName,@{Name="UpTimeHours"; Expression = {$_.UpTimeHours.ToString("#.##")}} | Select-Object -First 4 |`
Format-Table -AutoSize -OutVariable $Top4.ToString()
foreach ($Server in $Top4.ComputerName) {
Invoke-Command -ComputerName $Server -ScriptBlock {HOSTNAME.EXE}
}
我沒有在最后一個 foreach 中與 Invoke-Command 結婚,但是當我嘗試使用 psexec 時遇到了同樣的問題。此外,我正在運行 hostname.exe 作為檢查,以確保在我將其指向我的腳本之前回圈通過正確的機器。
uj5u.com熱心網友回復:
這是您的代碼的簡化版本,它聽取了對問題的評論:
# Get all computers of interest.
$computers = Get-ADComputer -Filter 'ObjectClass -eq "Computer"' -SearchBase "OU=***,OU=***,OU=***,DC=***,DC=***" -SearchScope Subtree
# Get the computers' up-times in hours.
# The result will be [double] instances, but they're also decorated
# with .PSComputerName properties to identify the computer of origin.
$upTimes = Invoke-Command -ComputerName $computers.ConputerName {
((Get-Date) - (Get-CimInstance -Class Win32_OperatingSystem).LastBootUpTime).TotalHours
}
# Get the top 4 computers by up-time.
$top4 = $upTimes | Sort-Object -Descending | Select-Object -First 4
# Invoke a command on all these 4 computers in parallel.
Invoke-Command -ComputerName $top4.PSComputerName -ScriptBlock { HOSTNAME.EXE }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/358616.html
標籤:电源外壳
