windows - 在运行提升的 session 时加载不同的 powershell 配置文件的技术是什么

标签 windows powershell profile elevated-privileges

如果我启动一个提升的 Powershell session ,我想在我的配置文件中包含一些内容,例如连接到映射的网络驱动器,以及作为奖励改变提示的颜色以提醒我我令人敬畏的提升的权力。

如果我用 #Requires -RunAsAdministrator 创建一个模块,然后将这一行添加到我的 profile.ps1 文件中

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

它可以很好地处理提升的 session ,但每次我打开一个普通 session 时,我都会收到一条红色的大错误消息,这在某种程度上不是最佳的。

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;

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

最佳答案

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

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

关于windows - 在运行提升的 session 时加载不同的 powershell 配置文件的技术是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45054464/

相关文章:

iOS Facebook SDK 获取头像

java - 在达到 Max 之前 PermGen 空间不足

php - 用户配置文件显示依赖于 php 所有者的信息

windows - 键盘无法使用 Teamviewer 9

windows - 批处理命令仅从字符串中获取文件路径

arrays - 是否可以在 PowerShell 中使 IndexOf 不区分大小写?

powershell - 将参数从批处理文件传递到 PowerShell 脚本

windows - Windows 上 Go 中的高分辨率计时器(毫秒精度)

c++ - 自定义窗口皮肤,

powershell - 使用 powershell 从 Azure 获取经典 VM 的虚拟机位置