首页 > 解决方案 > 使用“-noprofile”参数提升当前脚本

问题描述

我目前正在使用以下代码通过将代码放在我的脚本开头来提升我当前的脚本。我还想在提升脚本时包含“-noprofile”参数。如何在$newProcess.Arguments行中包含-noprofile

$myWindowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent();
$myWindowsPrincipal = New-Object System.Security.Principal.WindowsPrincipal($myWindowsID);
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator;

if ($myWindowsPrincipal.IsInRole($adminRole))
{

    $Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)";
    #$Host.UI.RawUI.BackgroundColor = "DarkBlue";
    Clear-Host;

} else {

    $newProcess = New-Object System.Diagnostics.ProcessStartInfo "PowerShell";
    $newProcess.Arguments = "& '" + $script:MyInvocation.MyCommand.Path + "'"
    $newProcess.WindowStyle = 'Hidden'
    $newProcess.CreateNoWindow = $True
    $newProcess.Verb = "runas";
    [System.Diagnostics.Process]::Start($newProcess);
    Exit;
}

标签: windowspowershell

解决方案


Arguments即使脚本路径包含空格,以下属性设置也应该起作用:

$newProcess.Arguments = "-NoProfile -Command `"& '$($script:MyInvocation.MyCommand.Path)' `""

另一种选择:

$newProcess.Arguments = "-NoProfile -File `"$($script:MyInvocation.MyCommand.Path)`""

推荐阅读