2017-02-11 180 views
1

我可以右鍵單擊DEC16.bat文件並運行。我無法將其包含在腳本中以便從閃存驅動器運行。 PowerShell腳本實質上是將一堆安裝文件複製到客戶機的計算機上。嘗試使用runas運行.bat文件時出錯使用PowerShell的管理員

Windows PowerShell 
Copyright (C) 2013 Microsoft Corporation. All rights reserved. 

PS H:\> $script = "\\xxxhsfmsl03\adap\Database\Install\AugKA\DEC16.bat" 
PS H:\> 
PS H:\> Start-Process powershell -Credential 「xxx\xxxvis_desktop」 -ArgumentList '-noprofile -command &{Start-Process $script -verb runas}' 
Start-Process : This command cannot be run due to the error: The directory name is invalid. 
At line:1 char:1 
+ Start-Process powershell -Credential 「xxx\xxxvis_desktop」 -ArgumentList '-noprof ... 
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo   : InvalidOperation: (:) [Start-Process], InvalidOperationException 
    + FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand 

PS H:\> $script 
\\xxxhsfmsl03\adap\Database\Install\AugKA\DEC16.bat 
PS H:\> 

(我已經插入的 「XXX」 的保護無辜者)

+1

參數列表是引用單引號。因此$ script不會展開。使用雙引號 – Matt

+1

如果你從[這裏]得到這段代碼(http://stackoverflow.com/questions/15305696/running-a-bat-file-as-admin-from-powershell)我明白了。我看你昨天在那裏留言。我還留下了一個指出錯誤。 – Matt

回答

0

嘗試以下操作:

Start-Process powershell ` 
    -WorkingDirectory (Split-Path $script) ` 
    -Credential xxx\xxxvis_desktop ` 
    -ArgumentList '-noprofile', '-command', " 
    & { start-process powershell -ArgumentList '-File', '$script' -Verb RunAs } 
    " 
  • 您的主要問題是最有可能的目標用戶 - xxx\xxxvis_desktop - 在調用時沒有權限訪問目前的目錄

    • 明確設置工作目錄到目錄目標用戶允許訪問應該解決這個問題 - -WorkingDirectory (Split-Path $script)設置工作目錄。到dir。目標腳本所在的位置。由Matt在關於這個問題的評論中指出 - -
  • 你的第二個問題是,你傳遞給Start-Process命令字符串被封閉在'...'引號),導致嵌入式$script可變參考而不是待擴展(內插)。

    • 使用"..."引號)修復的問題;請注意,要傳遞給powershell可執行文件的命令行被拆分爲個別參數通過-ArgumentList傳遞 - (文字,單引號)選項,後跟(插入的,雙引號)命令字符串,其中是傳遞參數的首選方式,因爲它更強大。

    • 注意,該命令串內的$string參考是如何封閉在嵌入'...'以便確保當調用powershell實例解析命令串,的$string值被識別爲單個參數(儘管這對於手頭的價值來說不是必要的,但是\\xxxhsfmsl03\adap\Database\Install\AugKA\DEC16.bat)。

      • 如果有一個機會的$script值已嵌入'的情況下,你必須使用以下(雙'情況下逃脫他們):
        $($script -replace "'", "''")
  • 最後問題在於你不能直接在腳本上使用Start-Process - 如在外部呼叫中,您需要呼叫powershell並將腳本傳遞給它文件名作爲參數。


其他注意事項:

  • 周圍的命令字符串的start-process調用的& { ... }包裝不應該是必要的。

  • 一般情況下,你可以使用一個Start-Process調用與-Verb RunAs提升的$script運行,但不幸的是,-Verb RunAs-Credential不能合併,這樣就意味着:

    • 如果當前用戶是一個管理帳戶,提升的會話將始終以該用戶的身份運行 - 您只會收到是/否提示以確認提升。
    • 否則,將提示輸入憑據,但不能在該對話框中預先填充用戶名。

    • Start-Process -Verb RunAs powershell -ArgumentList '-noprofile', '-File', $script

+1

它的工作原理。而且你是正確的,我不能通過放置「-Credential myUserNameHere」:::來預先填充用戶名,並且非常感謝你! – JustJohn

相關問題