问题描述
大家好,
我有一个Powershell脚本,它运行正常,但我想用另一行扩展它。这就是我所拥有的。
$Path = "\\xyz\trigger1.txt"
$Path2 = "$env:userprofile\xyz\trigger2.txt"
if ((Test-Path $Path -PathType Leaf) -and (-not(Test-Path $Path2 -PathType Leaf))){
if((get-process "XXX" -ea SilentlyContinue) -eq $Null)
{
"not Running"
copy-item "\\xyz\xyz\*" "$env:userprofile\def\" -recurse -ErrorAction SilentlyContinue
start-sleep -s 5
}
else
{
"running"
stop-process -name "XXX" -force
start-sleep -s 5
copy-item "\\xyz\xyz\*" "$env:userprofile\def\" -recurse -ErrorAction SilentlyContinue
start-sleep -s 5
}
}
else
{
start-sleep -s 5
}
现在,我想使用一个函数来扩展该脚本,该函数首先会检查服务器是否可用。如果不是,则应使用永久测试连接,直到可用为止。服务器可用时,脚本应继续运行。
解决方法
您可以尝试以下方法:
Do
{
Test-Connection -ComputerName $computerName -ErrorAction SilentlyContinue -ErrorVariable pingError | Out-Null
$pingError = $pingError | Where-Object { $_.CategoryInfo.Category -Eq 'ResourceUnavailable' }
Start-Sleep -Seconds 5
}
While($pingError -Ne $Null)
仅当没有出现ResourceUnavailable类型的错误时,脚本才会退出此循环。