如何导入仅供管理员使用的 PowerShell 模块?

How to import a PowerShell module for administrators only?

导入 PowerShell 模块时

#Requires -RunAsAdministrator

从我的 PowerShell 配置文件中,它抛出一个 ScriptRequiresElevation,Microsoft.PowerShell.Commands.ImportModuleCommand 错误。

我怎么办

最简单的方法是在您的配置文件脚本中添加条件检查,您可以添加检查以查看您是否 运行 作为管理员:

$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
if($currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
{
    Import-Module NeedsAdminModule
}