我试图弄清楚如何使用提升的凭据运行 powershell 脚本,并被告知最好的方法是使用 Start-Process
而这个网站,http ://social.technet.microsoft.com/Forums/windowsserver/en-US/132e170f-e3e8-4178-9454-e37bfccd39ea/startprocess-verb-runas-credential也是很好的参考
但我仍然有麻烦。
我创建了一个脚本用于测试目的,hello.ps1
write-host Hello World
它本身运行良好
然后,我创建了另一个脚本来使用提升的凭据调用 Hello World
<#Previously created password file in C:\Script\cred.txt, read-host -assecurestring | convertfrom-securestring | out-file C:\Script\cred.txt#>
$password = get-content C:\Script\cred.txt | convertto-securestring
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist "DOMAIN\Username",$password
$script = "C:\script\hello.ps1"
Start-Process powershell -Credential $credentials -verb runas -ArgumentList "-file $script"
我得到错误:
At C:\script\my_script.ps1:6 char:14
+ Start-Process <<<< powershell -Credential $credentials -verb runas -ArgumentList "-file $script"
+ CategoryInfo : InvalidArgument: (:) [Start-Process], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands.StartProcessCommand
编辑
@Adi Inbar
我更新了代码如下
$password = get-content C:\Script\cred.txt | convertto-securestring
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist "DOMAIN\Username",$password
$script = "C:\Script\hello.ps1"
Start-Process powershell -Credential $credentials -ArgumentList "-file $script"
但是现在弹出一个 cmd 窗口并且输出为空白,而不是预期的“Hello World”
编辑
而且我读到如果包含-Credential,则必须包含-FilePath,但代码仍然无法正常工作:-(
它只是弹出cmd窗口,powershell_ise.exe GUI中没有输出
<#Previously created password file in C:\Script\cred.txt, read-host -assecurestring | convertfrom-securestring | out-file C:\Script\cred.txt#>
$password = get-content C:\Script\cred.txt | convertto-securestring
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist "DOMAIN\Username",$password
$script = "C:\Script\hello.ps1"
Start-Process -FilePath C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Credential $credentials -ArgumentList "-file $script"