如何以不同的用户身份执行PS1文件?
我需要能够以不同的用户身份远程运行PowerShell脚本(通过Jenkins)。由于它将作为詹金斯的工作执行,Get-Credential
不适合我。下面是我创建的脚本,但它不起作用。如何以不同的用户身份执行PS1文件?
$uname='domain\username'
$pwd='password'
$passw=Convertto-SecureString -String $pwd -AsPlainText -force
$mycred=New-object -TypeName System.Management.Automation.PSCredential -ArgumentList $uname, $passw
Invoke-Command -FilePath "C:\test_scripts\fetchquery.ps1" -Authentication default -Credential $mycred -computername localhost
创建凭据对象:
$username = 'domain\username'
$Password = 'password' | ConvertTo-SecureString -Force -AsPlainText
$credential = New-Object System.Management.Automation.PsCredential($username, $Password)
在你的代码执行它在本地主机上,因此开始PowerShell会话使用保存的凭证:
Start-Process powershell -argumentlist '-executionpolicy','bypass','-file',"C:\test_scripts\fetchquery.ps1"' -Credential $credential
并远程运行脚本(不要使用本地主机)
Invoke-Command -Computername 'Computer' `
-FilePath C:\test_scripts\fetchquery.ps1 -ArgumentList PowerShell `
-Cred $Credential
嗨@Avshalom,感谢您修复脚本。它在本地运行时效果很好。但是,因为詹金斯不允许任何弹出窗口,它会阻止脚本执行。我尝试'-WindowStyle Hidden'到-ArgumentList,但它错误与以下内容:**参数集不能使用指定的命名参数解析** – Karthik
Jenkins将构建标记为Success,但eventviewer在系统日志下有此错误:* *应用程序弹出:powershell.exe - 应用程序错误:应用程序无法正确启动(0xc0000142)。点击确定关闭应用程序**。任何想法如何我可以抑制这个小小的黑色命令窗口被盗取? - 谢谢。 – Karthik
试试这个:
Start-Process powershell -WindowStyle 'Hidden' -ArgumentList '-executionpolicy', 'bypass', '-file', $scriptFullName -Credential $C
这是一个复制和粘贴事故,把两条线放在一起? '$ mycred = New-object .....'应该在它自己的行上。 – Matt
定义“不起作用”。 –