2017-07-12 55 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

相關問題