【发布时间】:2021-12-22 01:34:44
【问题描述】:
我想在找不到服务或机器离线时打印错误消息
$csv = Import-Csv "C:\Users\user\Desktop\computers.csv" -delimiter ","
foreach ($cs in $csv){
$computers = $cs.DNSHostname
foreach ($computer in $computers){
Try{
Invoke-Command -ComputerName $computer -ScriptBlock {
$ProcessCheck = Get-Process -Name agentid-service -ErrorAction Stop
if ($null -eq $ProcessCheck) {
Write-output "agentid-service IS not running $env:computername"
}
else {
Write-output "agentid-service IS running $env:computername"
}
}
}
catch{
Write-Warning $Error[0]
}
}
}
相反,当找不到服务名称时,我得到了错误:
Cannot find a process with the name "agentid-service". Verify the process name and call the cmdlet again.
如果无法连接到计算机,则获取:
[vm.domain.local] Connecting to remote server vm.domain.local failed with the following error message : The WinRM client cannot process the request because the server name cannot be resolved.
脚本继续执行(应该如此)。 如何让“Catch”块被执行?
【问题讨论】:
标签: powershell error-handling try-catch invoke-command