2017-07-12 38 views
2

如果我启动一个提升的powershell会话,我想在我的配置文件中包含一些内容,比如连接到映射的网络驱动器,以及作为额外的改变提示的颜色让我想起我的真棒提升的力量。在运行提升的会话时加载不同的PowerShell配置文件有什么技巧

如果我创建一个模块#Requires -RunAsAdministrator在它的前面,然后将此行添加到我的profile.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; 

是否有检测当前会话是否升高与否的方法吗?

回答

1

看起来你可以检查管理员权限如下:

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

相关问题