我試圖找出如何使用提升的憑據運行PowerShell腳本,被告知要做到這一點的最好辦法是用開始處理PowerShell的 - 啓動過程中推出的hello world不工作
但我仍然有麻煩。
我創建用於測試目的一個腳本,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因巴爾
我更新的代碼如下
$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」
編輯
而且我讀到你必須包含-FilePath如果包含-Credential,但代碼仍然是不工作:-(
它只是彈出,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"
但你知道,這是我所說的相反嗎?是的,我在下面看到您的評論,並且我明白您確實需要以其他帳戶身份運行,但這並沒有改變這樣一個事實:具有本地管理員權限的憑證的「-Credential $ credential」不會自動爲您提供提升會話,就像以本地管理員身份登錄時交互啓動PowerShell一樣,默認情況下不會爲您提供高級會話。 –