Powershell脚本阻止Windows服务无法正常工作。也没有抛出错误

时间:2017-10-01 17:46:50

标签: windows powershell

此脚本具有接受参数(要停止的服务)的功能。我按照以下方式运行脚本。但服务不会停止。也出于某种原因,没有任何内容写入控制台。写主机在哪里写?我在Windows 8操作系统上使用Powershell版本4.0。

  .\MywindowsService.ps1 Dhcp -force 

  function StopWindowsService
  {
         Param([string] $ServiceName)
         $aService = Get-Service -Name $ServiceName
        if ($aService.Status -ne "Stopped")
        {
               Stop-Service $ServiceName
               Write-Host "Stopping " $ServiceName " service" 
               " ---------------------- " 
              " Service is now stopped"
         }

        if ($aService.Status -eq "stopped"){ 
             Write-Host "$ServiceName service is already stopped"
        }

   }

1 个答案:

答案 0 :(得分:1)

你可以尝试这个 - mywindowsservice.ps1:

Param([string] $ServiceName)

$aService = Get-Service -Name $ServiceName

if ($aService.Status -ne "Stopped") {
    Stop-Service $ServiceName
    Write-Host "Stopping " $ServiceName " service"
    " ---------------------- "
    " Service is now stopped"
}

if ($aService.Status -eq "stopped") {
    Write-Host "$ServiceName service is already stopped"
}

拨打:

.\mywindowsservice.ps1 dhcp

声明function StopWindowsService表示您需要在ps1文件中调用StopWindowsService来实际执行代码。这里不需要它。