我收到这个错误。
Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At F:\Code\powershell\network_shutdown\TurnNetworkOff.ps1:19 char:26
+ Get-WmiObject <<<< -computername $computer Win32_NetworkAdapter -filter "AdapterTypeId
=0" | % {
+ CategoryInfo : InvalidOperation: (:) [Get-WmiObject], COMException
+ FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
这是我的代码
#Define variables used in this script
$namespace = "root\WMI"
$array = @()
$exceptionarray = @()
$computerlist = Get-Content F:\Code\powershell\network_shutdown\computer-list.csv
foreach ($computer in $computerlist)
{
# Main Processing Section
# Write-Host $computer
if((Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet))
{
Try
{
#Write-Host $computer
#Write-Host "Disable `"Allow the computer to turn off this device to save power`""
Get-WmiObject -computername $computer Win32_NetworkAdapter -filter "AdapterTypeId=0" | % {
$strNetworkAdapterID=$_.PNPDeviceID.ToUpper()
Get-WmiObject -class MSPower_DeviceEnable -computername $computer -Namespace $namespace | % {
if($_.InstanceName.ToUpper().startsWith($strNetworkAdapterID))
{
$_.Enable = $false
$_.Put() | Out-Null
}
}
}
#Write-Host "Disable `"Allow this device to wake the computer`""
Get-WmiObject -computername $computer Win32_NetworkAdapter -filter "AdapterTypeId=0" | % {
$strNetworkAdapterID=$_.PNPDeviceID.ToUpper()
Get-WmiObject -class MSPower_DeviceWakeEnable -computername $computer -Namespace $namespace | % {
if($_.InstanceName.ToUpper().startsWith($strNetworkAdapterID)){
$_.Enable = $false
$_.Put() | Out-Null
}
}
}
#Write-Host "Disable `"Only allow a magic packet to wake the computer`""
Get-WmiObject -computername $computer Win32_NetworkAdapter -filter "AdapterTypeId=0" | % {
$strNetworkAdapterID=$_.PNPDeviceID.ToUpper()
Get-WmiObject -class MSNdis_DeviceWakeOnMagicPacketOnly -computername $computer -Namespace $namespace | % {
if($_.InstanceName.ToUpper().startsWith($strNetworkAdapterID)){
$_.EnableWakeOnMagicPacketOnly = $false
$_.Put() | Out-Null
}
}
}
} Catch [Exception]
{
Write-Host $computer + " WMIC ERROR"
if ($_.Exception.GetType().Name -eq "COMException") {
Write-Host $computer + " WMIC ERROR"
}
$output = new-object psobject
$output | Add-Member noteproperty PCTag $computer
[PSObject[]]$exceptionarray += $output
}
} else {
Write-Host $computer + " OFFLINE"
$output = new-object psobject
$output | Add-Member noteproperty PCTag $computer
[PSObject[]]$array += $output
}
$array | Export-Csv -Path F:\Code\powershell\network_shutdown\ResultsOffline.csv
$exceptionarray | Export-Csv -Path F:\Code\powershell\network_shutdown\ResultsException.csv
}
这
GetWMICOMException
是一个非终止错误,这意味着在默认情况$ErrorActionPreference
下Continue
,块中的代码try
将在将异常写为错误后继续执行Get-WmiObject
用块括住调用try-catch
,但确保-ErrorAction
设置为Stop
:或者,您可以在执行脚本之前将其设置
$ErrorActionPreference
为:Stop
有关 try-catch-finally 构造的更多帮助:
有关
$*Preference
变量的更多帮助: