我正在尝试将当前进程的值存储在powershell脚本的else语句中。我用“Global:varname”来存储。此过程调用另一个提升的PowerShell进程,我需要此变量值来关闭调用者进程。当我尝试在else语句之外打印全局变量时,它会打印初始值而不是PID。
我的脚本看起来像这样:
# Get the ID and security principal of the current user account
$global:some = 'some global' //declaring the global variable
$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))
{
Write-Host $PID
# 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";
# 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
[System.Diagnostics.Process]::Start($newProcess);
Set-Variable -Name $some -Value $PID -Scope Global //setting the value of PID to the global variable
# Exit from the current, unelevated, process
Write-Host $global:some
exit
}
Write-Host $global:some //this comes out to be initialized value rather then PID
# Run your code that needs to be elevated here
#Write-Host -NoNewLine "Press any key to continue..."
#$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")