运行 提升会话时加载不同 powershell 配置文件的技术是什么

What's the technique for loading a different powershell profile when running an elevated session

如果我启动提升的 Powershell 会话,我想在我的配置文件中包含一些内容,例如连接到映射的网络驱动器,以及作为奖励更改提示的颜色以提醒我我很棒的提升权力。

如果我创建一个前面带有#Requires -RunAsAdministrator的模块,然后将这一行添加到我的配置文件中。ps1文件

  Import-Module ($PSScripts + "elevated.ps1");

它可以很好地处理提升的会话,但每次我打开一个普通会话时,我都会收到一条红色的大错误消息,这有点不理想。

Import-Module : The script 'elevated.ps1' cannot be run because it contains a "#requires" statement for running as Administrator. The current Windows
PowerShell session is not running as Administrator. Start Windows PowerShell by  using the Run as Administrator option, and then try running the script again.
At C:\Users\sdixon.MV\Documents\WindowsPowerShell\profile.ps1:22 char:3
+   Import-Module ($PSScripts + "elevated.ps1") -ErrorAction silentlyco ...
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (elevated.ps1:String) [Import-Module], ScriptRequiresException
    + FullyQualifiedErrorId : ScriptRequiresElevation,Microsoft.PowerShell.Commands.ImportModuleCommand

即使我尝试使用也会发生这种情况:

  Import-Module ($PSScripts + "elevated.ps1") -ErrorAction silentlycontinue;

有没有办法检测当前会话是否被提升?

看来您可以按如下方式检查管理员权限:

If (([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")){
    Import-Module ($PSScripts + "elevated.ps1")
} Else {
    Write-Warning 'You do not currently have Administrator rights.'
}

来源:https://blogs.technet.microsoft.com/heyscriptingguy/2011/05/11/check-for-admin-credentials-in-a-powershell-script/

他还编写了一个 Test-IsAdmin 函数,可在此处的脚本库中找到:https://gallery.technet.microsoft.com/scriptcenter/1b5df952-9e10-470f-ad7c-dc2bdc2ac946