PS 用于检查服务状态并安装新 windows 服务的脚本
PS script to check status of a service and install a new windows service
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
你可以使用
$service = Get-Service -Name XXX -Computername YYY -ErrorAction SilentlyContinue
抑制错误。
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
你可以使用
$service = Get-Service -Name XXX -Computername YYY -ErrorAction SilentlyContinue
抑制错误。