ant*_*nio 3 powershell cmd batch-file elevated-privileges executionpolicy
我有一个 PowerShell 设置,我想在执行策略可能受到限制并且需要管理员权限的计算机上执行。
理想情况下,我可以将其包装在 cmd 批处理中,如下所示:
powershell -Command "Start-Process powershell -Verb runAs -ArgumentList '-noexit','-ExecutionPolicy','bypass','-File','C:\path\setup.ps1'"
Run Code Online (Sandbox Code Playgroud)
问题是,当包含空格时,我无法使其工作C:\path\setup.ps1,并且如果相对(使用 ),路径也不起作用cd C:\path。
有什么帮助吗?
在Windows PowerShell中(请参阅PowerShell (Core) 7+的底部部分),使用提升权限(以管理员身份)Start-Process -Verb RunAs启动命令时,总是用作  工作目录- 即使存在参数,也会被悄悄忽略。
因此,为了设置自定义工作目录并在其中调用脚本,必须使用 CLI 参数,并且( ) 调用必须先于调用由C:\Windows\SYSTEM32-WorkingDirectory-CommandSet-Locationcd ) 调用必须先于对相对。
虽然将传递参数单独传递给Start-Processcmdlet 的  参数在-ArgumentList概念上可能更可取,但不幸的是,长期存在的错误使得将所有参数编码在单个字符串中更好- 请参阅此答案。
cmd.exe通过powershell.exeWindows PowerShell CLI执行所有这些操作会由于转义要求而使事情变得复杂。
应用于您的powershell.exeCLI 调用,
假设工作目录。C:\path 1和脚本文件setup 1.ps1:
powershell -Command "Start-Process -Verb RunAs powershell '-NoExit -ExecutionPolicy Bypass -Command cd \\\"C:\path 1\\\"; & \\\".\setup 1.ps1\\\"' "
Run Code Online (Sandbox Code Playgroud)
注意如何嵌入"字符。双重转义,如\\\":首先 as\"以便在外部 powershell.exe调用期间保留,然后再次转义内部调用。
虽然这通常有效,但在某些边缘情况下\基于 - 的转义是不够的,即如果脚本路径或文件名包含cmd.exe元字符,例如&; 在这种情况下,"^""(sic) 必须用于第一轮 -"转义:
powershell -Command "Start-Process -Verb RunAs powershell '-NoExit -ExecutionPolicy Bypass -Command "^"" cd \\"^""C:\path 1\\"^""; & \\"^"".\setup 1.ps1\\"^"" "^""'"
Run Code Online (Sandbox Code Playgroud)
笔记:
从cmd.exe(batch files) , (sic) 是将嵌入整个字符串的内容"^""传递到 的最可靠的方法,如上所示,而它是""..."powershell.exe""pwsh.exePowerShell (Core) CLI(见下文)。
相比之下,从无shell上下文(例如计划任务)\"工作都非常稳健。
有关详细信息,请参阅此答案。
当您调用pwsh.exePowerShell (Core) 7+ CLI时,可以进行简化,甚至可能不需要解决方法:
pwsh.exe 默认情况下,即使使用 ,也确实保留调用者的工作目录-Verb RunAs,并且确实尊重.-WorkingDirectory-Verb RunAs
除了 之外\",pwsh.exe更简单的是支持""嵌入"字符。在字符串中"...";后者工作稳健cmd.exe
pwsh.exe它本身现在有一个-WorkingDirectory参数,因此允许使用该-File参数调用脚本:
pwsh.exe -WorkingDirectory "C:\path 1" -Command "Start-Process -Verb RunAs pwsh.exe '-NoExit -ExecutionPolicy Bypass -File ""C:\path 1\setup 1.ps1""'"
Run Code Online (Sandbox Code Playgroud)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           9078 次  |  
        
|   最近记录:  |