简体   繁体   中英

Powershell script to stop the windows service not working . No error is thrown either

This script has a function that accepts a parameter (service to be stopped). I ran the script the following way. But the service wouldn't stop. Also for some reason nothing is being written to the console. Where is the Write-Host is writing to? I am using Powershell Version 4.0 on windows 8 OS.

  .\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"
        }

   }

You could try this - 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"
}

Call:

.\mywindowsservice.ps1 dhcp

Declaring function StopWindowsService means you need to call StopWindowsService inside the ps1 file to actually execute the code. It is not needed here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM