Search code examples
powershellread-host

Powershell script to Stop and start windows Service using S.no


I have a listed my Windows Service Names in the Text file and I have added the code to display it by adding the S.no preceding to the Names,

Listofservices.txt contains

Print Spooler

Windows Update

Remote Desktop Services

Get-Content 'C:\Services\Listofservices.txt' | ForEach-Object  { $i = 1 } { "$i.$_" ; $i++ }

Result

  1. Print Spooler
  2. Windows Update
  3. Remote Desktop Services

now I would like to stop, start the services by entering only the S.no and I don't want to type the exact full name

$userinput = read-host -prompt "Enter the S.no to Stop/Start"
Stop-Service -Name "$userinput" -Force -Confirm

say for example if i enter the number 1 the Print Spooler service will be stopped


Solution

  • Here is one way you could do it following the code you already have, but as stated in comments, this is much simpler to do with Out-GridView -PassThru. Also do note, for these services, the PowerShell process will most likely require to be elevated.

    $file = Get-Content path\to\file.txt
    $file | ForEach-Object  { $i = 1 } { "$i.$_" ; $i++ }
    $userinput  = Read-Host "Enter the S.no to Stop/Start"
    try {
        $choice = $file[-1 + $userinput]
        if(-not $choice) {
            throw 'Invalid selection..'
        }
    
        $service = Get-Service $choice
        if('Running' -eq $service.Status) {
            $service.Stop()
            "$($service.Name) has been stopped.."
            return # end the script here
        }
    
        $service.Start()
        "$($service.Name) has been started.."
    }
    catch {
        if($_.Exception.InnerException.InnerException.NativeErrorCode -eq 5) {
            return "Process needs to be elevated."
        }
        "An error ocurred: $_"
    }