# New-ElevatedTask.ps1 # Creates a new "On Demand Only" scheduled task to run an "Elevated" application on Vista # This MUST be run from an elevated prompt, so by default it just uses the current user ID param( $application , $arguments = "" , $startIn = $(Split-Path $application) , $friendlyName = $(Split-Path $application -leaf) , $taskname = $("Elevated $friendlyName") , $user=$null , $password = $null , [System.Management.Automation.PSCredential]$credential = $null ) $xml = @" 2007-09-20T09:32:26.3036 {4} Run {0} "As Administrator" {4} {5} HighestAvailable PT10M PT1H true false Parallel false true true false false true true false false false P3D 7 {1} {2} {3} "@ $xFile = "$([IO.Path]::GetTempFileName())" # if they specify a user name, assume they want to do password authentication if($user -ne $null -and $password -ne $null) { $xml -f $friendlyName, $application, $arguments, $startin, $user, "Password" | set-content $xFile C:\Windows\system32\schtasks.exe /Create /XML $xFile /TN $taskname /RU $user /RP $password # if they didn't include a password, prompt them for one ... } elseif($user -ne $null -and $password -eq $null) { $xml -f $friendlyName, $application, $arguments, $startin, $user, "Password" | set-content $xFile C:\Windows\system32\schtasks.exe /Create /XML $xFile /TN $taskname /RU $user /RP # if they supplied credentials instead, use that } elseif($credential -ne $null) { $xml -f $friendlyName, $application, $arguments, $startin, $user, "Password" | set-content $xFile $BSTR = [System.Runtime.InteropServices.marshal]::SecureStringToBSTR($credential.Password); C:\Windows\system32\schtasks.exe /Create /XML $xFile /TN $taskname /RU $credential.UserName /RP ([System.Runtime.InteropServices.marshal]::PtrToStringAuto($BSTR)) [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($BSTR); } else { # if they suppplied neither user nor credentials, lets assume they want the "current" user $user = ([Security.Principal.WindowsIdentity]::GetCurrent().Name) # if they passed a password, use that if($password -ne $null) { $xml -f $friendlyName, $application, $arguments, $startin, $user, "Password" | set-content $xFile C:\Windows\system32\schtasks.exe /Create /XML $xFile /TN $taskname /RU $user /RP $password # otherwise, there are no special credentials needed, "Interactive" means only "this" user can run it. } else { $xml -f $friendlyName, $application, $arguments, $startin, $user, "InteractiveToken" | set-content $xFile C:\Windows\system32\schtasks.exe /Create /XML $xFile /TN $taskname } }