Starting Elevated PowerShell Windows

There are a few commands I have to run from Elevated PowerShell windows (such as suspending Bitlocker prior to patching).  It’s not that hard to right-click on my pinned-to-taskbar PowerShell icon and select “Run as Administrator”, but I wanted to see if I could avoid that.  I can, somewhat.  This throws up the UAC prompt once to create the scheduled task. It creates an icon on your desktop with the name “PSH (Admin)”. Double-click on this, and you’re in an elevated window.

 $taskName = "PowerShellRunAsAdmin";

if (!(Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue))
{
    Start-Process -Verb RunAs -FilePath schtasks.exe -ArgumentList  "/Create /TN $taskName /SC ONCE /TR `"$PSHome\powershell.exe`" /ST 00:00 /SD 01/01/2001 /RL Highest";
} # if (!(Get-ScheduledTask -TaskName $taskName))

if (!(Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue -ErrorVariable errorVariable))
{
    $message = "($($MyInvocation.MyCommand.Name)) $($errorVariable.Exception.Message -replace '[\r\n]', ' ')";
    Write-Error -ErrorAction SilentlyContinue -Message $message;
    Write-Warning -Message $message;
    return;
    break __outOfScript;

} # if (!(Get-ScheduledTask -TaskName $taskName))

$path = "$home\Desktop\PSH (admin).lnk";
if (!(Test-Path -Path $path))
{
    $shortcut = (New-Object -ComObject WScript.Shell).CreateShortcut($path);
    $shortcut.TargetPath = "schtasks.exe";
    $shortcut.Arguments = "/Run /TN PowerShellRunAsAdmin";
    $shortcut.IconLocation = (Get-Command -Name powershell.exe).Path;
    $shortcut.Save();
}

Why use a mix of Get-ScheduledTask and schtasks.exe?  Get-ScheduledTask is much more complex to call to create a task, but schtasks.exe requires we test on $LASTEXITCODE to see if a task is not present.