如何定义需要提升的 PowerShell 函数?

Lin*_*eak 21 uac powershell

由于我找不到 Linux 的sudo提升命令的任何替代方法,因此我有以下问题:

如何定义需要提升的 PowerShell 函数?我的意思是 UAC 提示。

说,这样的函数如下:

function system-check {
    SFC /ScanNow
}
Run Code Online (Sandbox Code Playgroud)

系统:

Windows 8.1 专业版 64 位

电源外壳:

Major  Minor  Build  Revision
-----  -----  -----  --------
5      0      10586  117
Run Code Online (Sandbox Code Playgroud)

编辑1:

为了 100% 可以理解,让我改写一下:

  1. 我以用户身份运行 PowerShell
  2. 我运行上述功能 system-check
  3. 我希望功能提升以便能够执行命令;请注意,我希望出现 UAC 提示

Ash*_*ton 37

要从提升的窗口运行特定命令:

Start-Process -FilePath powershell.exe -ArgumentList {$ScriptBlock} -verb RunAs
Run Code Online (Sandbox Code Playgroud)

例如:

Start-Process -FilePath powershell.exe -ArgumentList {
    SFC /scannow
} -verb RunAs
Run Code Online (Sandbox Code Playgroud)

要从提升的窗口运行特定脚本:

Start-Process powershell -ArgumentList '-noprofile -file MyScript.ps1' -verb RunAs
Run Code Online (Sandbox Code Playgroud)

要运行整个 PowerShell 会话提示 UAC:

Start-Process powershell.exe -Verb runAs
Run Code Online (Sandbox Code Playgroud)

如果当前窗口以提升的权限运行,则返回 $True 或 $False 的函数:

function isadmin
 {
 #Returns true/false
   ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
 }
Run Code Online (Sandbox Code Playgroud)

要确保脚本仅以管理员身份运行,请将其添加到开头:

If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
 {
  Echo "This script needs to be run As Admin"
  Break
 }
Run Code Online (Sandbox Code Playgroud)

在 PowerShell v4.0 中,可以使用 #Requires 语句简化上述操作:

#Requires -RunAsAdministrator
Run Code Online (Sandbox Code Playgroud)

来源:以提升的权限运行