PS脚本场景
1-> Check if service exists
-> if doesn't exists
-> copy item and install windows service and start.
-> If exists
-> Stop Windows service & delete it and copy item from folder and Install & start the service.
以下是我的剧本
$service = Get-Service -Name XXX -Computername YYY
if($service.Status -eq $NULL)
{
Copy-Item "C:\location\*" "\\yyy\d$\Location" -Force -Recurse
sc.exe \\yyy create xxx start=auto DisplayName="value" binPath= D:\Build\test.exe
sc.exe \\yyy description xxx "value"
sc.exe \\yyy start xxx
Write-Host "xxx STARTED"
}
else
{
sc.exe \\yyy stop xxx
Write-Host "xxx STOPPED"
sc.exe \\yyy delete xxx
Write-Host "xxx DELETED"
Copy-Item "C:\Location\*" "\\yyy\d$\Location" -Force -Recurse
sc.exe \\yyy create xxx start=auto DisplayName="value" binPath= D:\Build\test.exe
sc.exe \\yyy description xxx "value"
sc.exe \\yyy start xxx
Write-Host "xxx STARTED"
}
我的方法是否正确,如果没有服务名称XXX,我会看到错误。如何覆盖此错误并继续使用If条件语句。
错误 -
Get-Service : Cannot find any service with service name 'Spoole'.
At line:1 char:12
+ $service = Get-Service -Name Spoole
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Spoole:String) [Get-Service], ServiceCommandException
+ FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.GetServiceCommand
答案 0 :(得分:1)
您可以使用
$service = Get-Service -Name XXX -Computername YYY -ErrorAction SilentlyContinue
压制错误。