通常,要在 Windows 上以编程方式调用具有提升(以管理员身份运行)的可执行文件,请使用 Start-Process cmdlet 和 -Verb RunAs。
这同样适用于pwsh.exe,PowerShell Core 可执行文件,因此在最简单的情况下您可以编写:
# Open a new console window with PowerShell Core running with admin privileges.
Start-Process -Verb RunAs pwsh
如果您想将其封装在一个便捷功能中,该功能也更强大且跨版本在 Windows 上(也适用于 Windows PowerShell):
-
注意:请参阅底部部分了解更复杂的功能,可从 Gist 下载,该功能还允许传递 命令 以在提升的 PowerShell 会话中执行。
function Enter-AdminPSSession {
Start-Process -Verb RunAs (Get-Process -Id $PID).Path
}
# Optionally also define a short alias name:
# Note: 'psa' is a nonstandard alias name; a more conformant name would be
# the somewhat clunky 'etasn'
# ('et' for 'Enter', 'a' for admin, and 'sn'` for session), analogous
# to built-in 'etsn' alias referring to 'Enter-PSSession'
Set-Alias psa Enter-AdminPSSession
如果您希望该功能也跨平台(也适用于类 Unix 平台):
function Enter-AdminPSSession {
if ($env:OS -eq 'Windows_NT') {
Start-Process -Verb RunAs (Get-Process -Id $PID).Path
} else {
sudo (Get-Process -Id $PID).Path
}
}
重要提示:由于涉及到 cmdlet/实用程序,
如果您还希望能够在新会话中运行命令并可选择自动关闭它,则需要做更多工作:
您可以从this Gist下载函数Enter-AdminPSSession,其中:
假设您已经查看了链接的 Gist 源代码以确保它是安全的(我可以亲自向您保证,但您应该经常检查),您可以直接安装Enter-AdminPSSession,如下所示:
irm https://gist.github.com/mklement0/f726dee9f0d3d444bf58cb81fda57884/raw/Enter-AdminPSSession.ps1 | iex
示例调用(假定Set-Alias psa Enter-AdminPSSession 已被调用):
psa
- Windows:在不加载配置文件的情况下进入提升的会话并设置所有用户执行策略,如果成功则退出。
psa -NoProfile -ExitOnSuccess { Set-ExecutionPolicy -Scope LocalMachine RemoteSigned }
- Unix:获取文件
/etc/sudoers的内容(只有管理员权限才能读取),然后退出:
psa -Exit { Get-Content /etc/sudoers }