2012-12-15 40 views
0

我試圖寫一個簡短的runas-admin函數,我可以傳遞另一個函數名稱作爲參數,並使用管理員權限執行該命令(或多或少地等同於Linux中的sudo)。當我嘗試運行這個函數時,它會持續運行,永遠不會結束,佔用大量的CPU。我是PowerShell的新手,那麼我的代碼有什麼問題嗎?如何在當前shell中使用管理權限在PowerShell中運行命令?

function runas-admin 
{ 
# Get the ID and security principal of the current user account 
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent() 
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID) 

# Get the security principal for the Administrator role 
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator 

# Check to see if we are currently running "as Administrator" 
if ($myWindowsPrincipal.IsInRole($adminRole)) 
{ 
    # We are running "as Administrator" - so change the title and background color to indicate this 
    $Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)" 
    $Host.UI.RawUI.BackgroundColor = "DarkBlue" 
    clear-host 
} 
else 
{ 
    # We are not running "as Administrator" - so relaunch as administrator 

    # Create a new process object that starts PowerShell 
    $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell"; 
    $newProcess.RedirectStandardError = $TRUE; 
    $newProcess.RedirectStandardOutput = $TRUE; 
    $newProcess.UseShellExecute = $FALSE; 
    # Specify the current script path and name as a parameter 
    $newProcess.Arguments = $myInvocation.MyCommand.Definition; 

    # Indicate that the process should be elevated 
    $newProcess.Verb = "runas"; 

    # Start the new process 
    $childProcess = [System.Diagnostics.Process]::Start($newProcess); 
    $childProcess.WaitForExit(); 
    Write-Output $childProcess.StandardOutput.ReadToEnd(); 
} 
} 

回答

1

或者你可以只用動詞runas例如爲:

Start-Process powershell.exe -Verb runas 
+0

據我所知,這將打開一個新的程序中運行Start-Process。我想在當前shell(即窗口)中運行命令 – keyneom

+0

您可以使用-NoNewWindow在當前shell中運行新的PowerShell進程。 –

+0

如果我嘗試使用像get-location這樣的函數,則會出現以下錯誤:啓動過程:由於錯誤,無法運行此命令:系統找不到指定的文件。當我嘗試使用時出現此錯誤-NoNewWindow開關啓動過程:參數集無法使用指定的命名參數解決。' – keyneom

相關問題