
因為我找不到 Linux 的任何替代品'sudo
海拔命令,我有以下問題:
如何定義需要提升的PowerShell函數?我的意思是UAC提示。
比如說,這樣的函數如下:
function system-check {
SFC /ScanNow
}
系統:
Windows 8.1 專業版 64 位
電源外殼:
Major Minor Build Revision ----- ----- ----- -------- 5 0 10586 117
編輯1:
為了 100% 可以理解,讓我重新表達:
- 我以使用者身分執行 PowerShell
- 我運行上述函數
system-check
- 我希望提升該功能以便能夠執行該命令;請注意,我希望出現 UAC 提示
答案1
若要從提升的視窗執行特定命令:
Start-Process -FilePath powershell.exe -ArgumentList {$ScriptBlock} -verb RunAs
例如:
Start-Process -FilePath powershell.exe -ArgumentList {
SFC /scannow
} -verb RunAs
若要從提升的視窗執行特定腳本:
Start-Process powershell -ArgumentList '-noprofile -file MyScript.ps1' -verb RunAs
若要執行提示 UAC 的整個 PowerShell 會話:
Start-Process powershell.exe -Verb runAs
如果目前視窗以提升的權限執行,則傳回 $True 或 $False 的函數:
function isadmin
{
#Returns true/false
([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
}
若要確保腳本僅以管理員身份執行,請將其新增至開頭:
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
Echo "This script needs to be run As Admin"
Break
}
在 PowerShell v4.0 中,可以透過使用 #Requires 語句來簡化上述內容:
#Requires -RunAsAdministrator
來源:以提升的權限運行