Powershell Run-As Script
Posted
by marc dekeyser
on Geeks with Blogs
See other posts from Geeks with Blogs
or by marc dekeyser
Published on Wed, 05 Dec 2012 07:59:25 GMT
Indexed on
2012/12/05
17:05 UTC
Read the original article
Hit count: 275
Filed under:
Disclaimer: This script is not of my own making. I found it on a share somewhere and it is so handy I started using in a bunch of scripts. To the writer: If you're out there, somewhere, when you see this, thank you!
Check if script is running as Adminstrator and if not use RunAs
# Use Check Switch to check if admin
param([Switch]$Check)
$IsAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()`
).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
if ($Check) { return $IsAdmin }
if ($MyInvocation.ScriptName -ne "")
{
if (-not $IsAdmin)
{
try
{
$arg = "-file `"$($MyInvocation.ScriptName)`""
Start-Process "$psHome\powershell.exe" -Verb Runas -ArgumentList $arg -ErrorAction 'stop'
}
catch
{
Write-Warning "Error - Failed to restart script with runas"
break
}
exit # Quit this session of powershell
}
}
else
{
Write-Warning "Error - Script must be saved as a .ps1 file first"
break
}
write-host "Script Running As Administrator" -foregroundcolor red
Write-host ""
Check if script is running as Adminstrator and if not use RunAs
# Use Check Switch to check if admin
param([Switch]$Check)
$IsAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()`
).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
if ($Check) { return $IsAdmin }
if ($MyInvocation.ScriptName -ne "")
{
if (-not $IsAdmin)
{
try
{
$arg = "-file `"$($MyInvocation.ScriptName)`""
Start-Process "$psHome\powershell.exe" -Verb Runas -ArgumentList $arg -ErrorAction 'stop'
}
catch
{
Write-Warning "Error - Failed to restart script with runas"
break
}
exit # Quit this session of powershell
}
}
else
{
Write-Warning "Error - Script must be saved as a .ps1 file first"
break
}
write-host "Script Running As Administrator" -foregroundcolor red
Write-host ""
© Geeks with Blogs or respective owner