I am preparing new computers. After applying an image, I run a PowerShell script for some post-image deployment steps. Some steps must be run as the new (current) user, like registry settings in HCCU, while others, peppered through the script, must be run elevated.
In my script, I call the RunElevated
function below for the code the requires elevation. I would like to share values and functions between elevated and non-elevated code blocks, but is that possible? I tried passing arguments when calling Start-Process powershell.exe but ran into the “Inception” problem of quotes within quotes, arguments within arguments.
function RunElevated($ScriptBlock)
{
write-host -NoNewline "`nStarting a new window with elevated privileges. Will return here after..."
$scriptBlockWithBefore = {
write-host "`nSTEPS RUNNING WITH ELEVATED PRIVILEGES...`n" @mildAlertColours
}
$scriptBlockAfter = {
Write-Host -nonewline "`nHit Enter to exit this mode. "
Read-Host
}
$scriptBlockToUse = [scriptblock]::Create($scriptBlockWithBefore.ToString() + "`n" + $ScriptBlock.ToString() + "`n" + $scriptBlockAfter)
$proc = Start-Process "powershell.exe" -Verb runas -ArgumentList "-command `"$scriptBlockToUse`"" -PassThru -WorkingDirectory $pwd.ToString()
$proc.WaitForExit()
if($proc.ExitCode -ne 0) {
write-host "ran into a problem."
}
}