问题
Heyy guys,
i have a powershell script which is working fine but i want to expand it with another line. Here is what i have.
$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
}
Now i want to expand that script with a function, that checks at first, if a server is available. if its not, it should use a permant test-connection until its available. When the server is available, the script should keep going.
回答1:
You can try this:
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)
The script will go out of this loop only when no error of type ResourceUnavailable occurs.
来源:https://stackoverflow.com/questions/63389087/powershell-function-if-test-connection-true