问题
I am trying to create a PowerShell script that will start/stop services on a remote computer, but prompt the user for all the values. I know the account that will be used; I just need to prompt the user for the password.
This is for Tomcat instances. The problem is the Tomcat service isn't always named the same on different servers (tomcat6, tomcat7). I need to be able to store the password encrypted and prompt to stop or start. Here is what I have so far. Any thoughts?
I am not sure if I have the -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:
This should get you started, it uses optional parameters for credential and service name, if you omit credentials it will prompt for them. If you omit the service name it will default to tomcat* which should return all services matching that filter. The result of the search is then piped into either stop or start as required.
As the computername accepts pipeline input you can pass in an array of computers, or if they exist in a file pipe the contents of that file into the script.
e.g.
Get-Content computers.txt | <scriptname.ps1> -Control Stop
Hope that 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
}
来源:https://stackoverflow.com/questions/16408448/how-to-start-stop-a-service-on-a-remote-server-using-powershell-windows-2008