[英]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 prompt the user for all the values. 我正在尝试创建一个PowerShell脚本,该脚本将启动/停止远程计算机上的服务,但提示用户输入所有值。 I know the account that will be used;
我知道将要使用的帐户; I just need to prompt the user for the password.
我只需要提示用户输入密码即可。
This is for Tomcat instances. 这是针对Tomcat实例的。 The problem is the Tomcat service isn't always named the same on different servers (tomcat6, tomcat7).
问题是Tomcat服务在不同服务器(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. 我不确定是否在正确的位置安装了
-AsSecureString
。
# 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
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.
如果您省略服务名称,它将默认为tomcat *,它将返回与该过滤器匹配的所有服务。 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. 由于计算机名接受管道输入,因此您可以传递计算机阵列,或者如果它们存在于文件管道中,则将该文件的内容传递到脚本中。
eg 例如
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.