如何以域用户身份运行Powershell脚本块?

时间:2018-10-12 14:14:29

标签: windows powershell active-directory

我有一个脚本块,试图使其以其他域用户身份运行。

$Username = 'domain\test'
$Password = '1234'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $UserName,$pass

Invoke-Command -ScriptBlock{
write-host "hello"

} -Credential $cred -ComputerName $env:COMPUTERNAME

当我运行它时,出现以下错误:

[test-pc] Connecting to remote server test-pc failed with the following error message : The client cannot connect to the destination specified in the request. Verify that the service on the destination is running and is accepting requests.
 Consult the logs and documentation for the WS-Management service running on the destination, most commonly IIS or WinRM. If the destination is the WinRM service, run the following command on the destination to analyze and configure the WinRM se
rvice: "winrm quickconfig". For more information, see the about_Remote_Troubleshooting Help topic.

为什么脚本试图在本地进行身份验证而不是针对DC? 谢谢

1 个答案:

答案 0 :(得分:1)

如果您实际上不想远程运行脚本,则可以使用Start-Process以另一个用户的身份运行Powershell ,然后该用户将以该用户的身份执行命令/脚本。

(有关完整的语法选项和示例,请参见powershell command line help

# Using Get-Credential to illustrate, substitute with your own credential code
$cred = Get-Credential

# Run Command:
Start-Process -FilePath Powershell -Credential $cred -ArgumentList '-Command', 'Write-Host "Hello"'

# Run Script:    
Start-Process -FilePath Powershell -Credential $cred -ArgumentList '-File', 'C:\folder\script.ps1'