我的计划如下:
我的 .ps1 文件名为
Start.ps1
,批处理文件名为 Start.bat
。
在当前的批量配置中,不会以管理员身份执行PS窗口,也不会允许脚本执行。
PowerShell -NoProfile -ExecutionPolicy Unrestricted -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Unrestricted -File ""C:\Users\user\Desktop\Install\StartNew.ps1""' -Verb RunAs}"
当目录为1:1时它确实有效,但在不同的机器上它不会开始安装chocolatey和winget。
将
Start.bat
和 Start.ps1
文件放在同一目录中。
在
Start.bat
中使用以下内容:
@echo off & setlocal
:: Determine the full path to the companion .ps1 file (Start.ps1)
:: based on the full path of this batch file (Start.bat)
set "PS1File=%~dpn0.ps1"
:: Now reference %PS1File% as part of the PowerShell command.
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "Start-Process -Verb RunAs PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File \"%PS1File%\"'"
注:
您仍然会收到 UAC 提示,要求授权创建提升的进程(只有停用 UAC 才能避免这种情况,强烈建议不要这样做)。
正如 Compo 所指出的,提升的进程会将
C:\Windows\System32
视为其工作目录;如果您的 .ps1
脚本需要不同的脚本(并且本身不会更改),则需要在调用脚本之前将嵌套 -File
切换到调用 -Command
的嵌套 Set-Location
调用。
要完全停用执行策略,请使用
-ExecutionPolicy Bypass
而不是 -ExecutionPolicy Unrestricted
,如上所示。 (这通常在实践中不会产生影响,但后者会提示输入从网络下载的脚本)。
没有理由使用 "& { ... }"
来调用通过
-Command
(-c
) 参数传递到 PowerShell CLI 的代码 - 只需直接使用 "..."
,如上面的代码所示。旧版本的 CLI 文档错误地建议
& { ... }
是必需的,但这已得到纠正。