posts - 104 , comments - 115 , trackbacks - 0

My Links

News

Disclaimer: Right here... Github: Code all the things! PS GUI Series: < Coming Soon! > PS Scripts: < Coming Soon! >

Tag Cloud

Archives

Post Categories

Blogs

Forums

Lync

Storage

Tools

Virtualization

Web comics

Powershell Run-As Script

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 ""

Print | posted on Wednesday, December 5, 2012 7:59 AM | Filed Under [ General Powershell ]

Feedback

No comments posted yet.
Post A Comment
Title:
Name:
Email:
Comment:
Verification:
 

Powered by: