在远程机器上停止或启动服务

在远程机器上停止或启动服务

本文介绍了在远程机器上停止或启动服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个脚本,该脚本将根据服务的显示名称启动或停止服务.我的脚本在本地机器上工作,但我想确保它可以在远程机器和本地机器上完成.我不知道如何让它在远程机器上工作.

I created a script that will start or stop a service based on it's display name. My script works on the local machine but I would like to make sure that it can be done on a remote machine and the local machine. I am not sure how to get it working on a remote machine.

任何帮助将不胜感激.

    $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"
}

推荐答案

假设您没有禁用 PowerShell 远程处理,最简单的方法是将其包装在一个函数中,并使用 ComputerName 作为可选参数,然后使用 Invoke-Command 和 splat PSBoundParameters.

Assuming that you have not disabled PowerShell remoting, the easiest way to do it is to wrap it in a function with ComputerName as an optional parameter, and then use Invoke-Command and splat PSBoundParameters.

Function Toggle-Service{
[cmdletbinding()]
Param([string[]]$ComputerName)
$serviceName = Read-Host -Prompt 'Please enter service name: '

# Check that service name exists
If (Invoke-Command -ScriptBlock {Get-Service $serviceName -ErrorAction SilentlyContinue} @PSBoundParameters)
{

# 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') {

Invoke-Command -ScriptBlock {Start-Service -displayname $serviceName} @PSBoundParameters

Write-Host $serviceName "Starting..." -ForegroundColor Green
}

#Stop service
If ($Choice -eq 'stop') {

  Invoke-Command -ScriptBlock {Stop-Service -displayname $serviceName} @PSBoundParameters

  Write-Host $serviceName "Stopping..." -ForegroundColor Green
}
 }
  }
else {
    Write-Host "Service name does not exist"
}
}

然后您可以不带参数调用 Toggle-Service 以在本地执行它,或包含远程服务器的名称以在该服务器上执行操作.

Then you can call Toggle-Service without a parameter to perform it locally, or include the name of a remote server to perform the actions on that server.

这篇关于在远程机器上停止或启动服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-20 22:51