我创建了一个脚本,它将根据服务的显示名称启动或停止服务。我的脚本可以在本地计算机上运行,但我想确保它可以在远程计算机和本地计算机上完成。我不知道如何让它在远程机器上工作。
任何帮助,将不胜感激。
$serviceName = Read-Host -Prompt 'Please enter service name: '
# Check that service name exists
If (Get-Service $serviceName -ErrorAction SilentlyContinue)
{
# Check that service name is not empty
if([string]::IsNullOrEmpty($serviceName))
{
Write-Host "Service name is NULL or EMPTY"
}
else
{
$Choice = Read-Host -Prompt 'Would you like to start or stop the service'
#Start service
If ($Choice -eq 'start') {
Start-Service -displayname $serviceName
Write-Host $serviceName "Starting..." -ForegroundColor Green
}
#Stop service
If ($Choice -eq 'stop') {
Stop-Service -displayname $serviceName
Write-Host $serviceName "Stopping..." -ForegroundColor Green
}
}
}
else {
Write-Host "Service name does not exist"
}
你不能使用Start-Service
/Stop-Service
然而,对于远程计算机,您可以从以下位置传递服务对象:Get-Service
(使用ComputerName
参数)到Set-Service
它可以对远程计算机执行相同的启动/停止操作:
Get-Service $ServiceName -ComputerName $ComputerName | Set-Service -Status Running
我发现这比使用 PowerShell Remoting 或 WMI 命令容易得多。
您可以通过最少的代码更改轻松更新代码:
$serviceName = Read-Host -Prompt 'Please enter service name: '
#get computername or use localhost for local computer
if(($ComputerName = Read-Host 'Enter Computer Name, leave blank for local computer') -eq ''){$ComputerName = 'localhost'}
$Service = Get-Service -DisplayName $serviceName -ComputerName $ComputerName -ErrorAction SilentlyContinue
# Check that service name exists
if ($Service) {
# Check that service name is not empty
if([string]::IsNullOrEmpty($serviceName)){Write-Host 'Service name is NULL or EMPTY'}
else {
$Choice = Read-Host -Prompt 'Would you like to start or stop the service'
#Start service
If ($Choice -eq 'start') {
$Service | Set-Service -Status Running
Write-Host $serviceName 'Starting...' -ForegroundColor Green
}
#Stop service
If ($Choice -eq 'stop') {
$Service | Set-Service -Status Stopped
Write-Host $serviceName 'Stopping...' -ForegroundColor Green
}
}
}
else {
Write-Host 'Service name does not exist'
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)