How to start / stop a service on a remote server using PowerShell - Windows 2008 & prompt for credentials?

I am trying to create a PowerShell script that will start / stop services on a remote computer, but ask the user for all the values. I know the account to be used; I just need to ask the user for a password.

This is for Tomcat instances. The problem is that the Tomcat service is not always called the same on different servers (tomcat6, tomcat7). I need to be able to store an encrypted password and invite to stop or start. Here is what I still have. Any thoughts?

I'm not sure that I have -AsSecureString in the right place.

 # Prompt for user credentials $credential=get-credential -AsSecureString -credential Domain\username # Prompt for server name $server = READ-HOST "Enter Server Name" # Prompt for service name $Service = READ-HOST "Enter Service Name" gwmi win32_service -computername $server -filter "name='$service'" -Credential' $cred.stop-service 
+1
source share
1 answer

This should get you started, it uses optional parameters for the credentials and service name, if you omit the credentials, they will request them. If you omit the service name, it will be the default for tomcat *, which should return all services matching this filter. The search result is then transmitted at any time or stopped as needed.

Since computer_name accepts the pipeline input, you can pass it to an array of computers or, if they exist in a file channel, the contents of this file in a script.

eg.

 Get-Content computers.txt | <scriptname.ps1> -Control Stop 

Hope this helps ...

 [cmdletBinding(SupportsShouldProcess=$true,ConfirmImpact="High")] param ( [parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string]$ComputerName, [parameter(Mandatory=$false)] [string]$ServiceName = "tomcat*", [parameter(Mandatory=$false)] [System.Management.Automation.PSCredential]$Credential, [parameter(Mandatory=$false)] [ValidateSet("Start", "Stop")] [string]$Control = "Start" ) begin { if (!($Credential)) { #prompt for user credential $Credential = get-credential -credential Domain\username } } process { $scriptblock = { param ( $ServiceName, $Control ) $Services = Get-Service -Name $ServiceName if ($Services) { switch ($Control) { "Start" { $Services | Start-Service } "Stop" { $Services | Stop-Service } } } else { write-error "No service found!" } } Invoke-Command -ComputerName $computerName -Credential $credential -ScriptBlock $scriptBlock -ArgumentList $ServiceName, $Control } 
+2
source

All Articles