Powershell(2.0版)使用凭据远程执行服务

Powershell(2.0版)使用凭据远程执行服务,powershell,windows-server-2008,powershell-2.0,Powershell,Windows Server 2008,Powershell 2.0,我想使用powershell 2.0版(Windows Server 2008)在远程计算机上启动/停止apache和mysql服务。我发现远程执行的语法如下: (Get-WmiObject -Computer myCompName Win32_Service -Filter "Name='myServiceName'").InvokeMethod("Stop-Service",$null) 但我也必须为这个例外提供凭证(域名\用户名和密码)。我是powershell新手,需要有关正确语法的帮

我想使用powershell 2.0版(Windows Server 2008)在远程计算机上启动/停止apache和mysql服务。我发现远程执行的语法如下:

(Get-WmiObject -Computer myCompName Win32_Service -Filter "Name='myServiceName'").InvokeMethod("Stop-Service",$null)

但我也必须为这个例外提供凭证(域名\用户名和密码)。我是powershell新手,需要有关正确语法的帮助(示例将易于理解和实现)。

获取WMIObject
接受
-Credential
参数。您不应该在脚本中以纯文本形式保存凭据,因此需要提示输入凭据

$creds = get-credential;
(Get-WmiObject -Computer myCompName Win32_Service -Filter "Name='myServiceName'" -credential $creds).InvokeMethod("Stop-Service",$null)
如果在远程系统上启用了PSRemoting,则可以在不使用WMI的情况下执行此操作

$creds = get-credential;
Invoke-Command -computername myCompName -credential $creds -scriptblock {(get-service -name myServiceName).Stop()};

根据评论更新

由于您将此作为计划作业运行,因此根本不应存储或提示输入凭据。已将计划作业本身(通过计划任务)配置为在所需的用户帐户下运行,则以下任一项都应起作用:

# Your original code
(Get-WmiObject -Computer myCompName Win32_Service -Filter "Name='myServiceName'").InvokeMethod("Stop-Service",$null)
# If you have remoting enabled
Invoke-Command -computername myCompName -scriptblock {(get-service -name myServiceName).Stop()};

Get WMIObject
接受
-Credential
参数。您不应该在脚本中以纯文本形式保存凭据,因此需要提示输入凭据

$creds = get-credential;
(Get-WmiObject -Computer myCompName Win32_Service -Filter "Name='myServiceName'" -credential $creds).InvokeMethod("Stop-Service",$null)
如果在远程系统上启用了PSRemoting,则可以在不使用WMI的情况下执行此操作

$creds = get-credential;
Invoke-Command -computername myCompName -credential $creds -scriptblock {(get-service -name myServiceName).Stop()};

根据评论更新

由于您将此作为计划作业运行,因此根本不应存储或提示输入凭据。已将计划作业本身(通过计划任务)配置为在所需的用户帐户下运行,则以下任一项都应起作用:

# Your original code
(Get-WmiObject -Computer myCompName Win32_Service -Filter "Name='myServiceName'").InvokeMethod("Stop-Service",$null)
# If you have remoting enabled
Invoke-Command -computername myCompName -scriptblock {(get-service -name myServiceName).Stop()};

谢谢你的快速回复。我想知道如何传递域名\用户名和密码。因为我需要创建调度任务,所以它不应该提示输入凭据。可以将详细信息存储在.txt文件中。我不是powershell程序员,所以如果我遗漏了什么,请告诉我。您作为计划任务执行此任务的事实应该在您的原始帖子中。您不应该在任何地方以纯文本形式存储凭据。配置要作为该用户执行的计划任务。然后跳过我帖子中关于凭证的所有内容。我错过了“运行”选项,因为特定用户将帮助我而不存储密码。作为管理员,我能够通过(get service-ComputerName myCompName-Name myServiceName).stop()启动/停止服务。我将按照你的建议执行我的要求。非常感谢。谢谢你的快速回复。我想知道如何传递域名\用户名和密码。因为我需要创建调度任务,所以它不应该提示输入凭据。可以将详细信息存储在.txt文件中。我不是powershell程序员,所以如果我遗漏了什么,请告诉我。您作为计划任务执行此任务的事实应该在您的原始帖子中。您不应该在任何地方以纯文本形式存储凭据。配置要作为该用户执行的计划任务。然后跳过我帖子中关于凭证的所有内容。我错过了“运行”选项,因为特定用户将帮助我而不存储密码。作为管理员,我能够通过(get service-ComputerName myCompName-Name myServiceName).stop()启动/停止服务。我将按照你的建议执行我的要求。谢谢。