Powershell – Run script from current directory and elevate as administrator

Posted: October 21, 2022 in Scripts

I created simple script to install FortiClient and put script and setup file in same folder and instead of specifying full path to FortiClientVPN.msi, wanted for script to locate full path of setup folder. Script will run if right click on it and select “Run with PowerShell”. Script will check if current user is Administrator, and if yes, it will elevate Powershell process, it’s equivalent to Run As admin.



function Test-Admin {
    $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())

if ((Test-Admin) -eq $false)  {
    if ($elevated) {
        # tried to elevate, did not work, aborting
    } else {
        Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))

# Restart Process using PowerShell 64-bit 
   Try {
       &"$ENV:WINDIR\SysNative\WindowsPowershell\v1.0\PowerShell.exe" -File $PSCOMMANDPATH
 Catch {
     Throw "Failed to start $PSCOMMANDPATH"

# Save the current location and switch to this script's directory.
# Note: This shouldn't fail; if it did, it would indicate a
# serious system-wide problem.

$prevPwd = $PWD; Set-Location -ErrorAction Stop -LiteralPath $PSScriptRoot

try {
 # Your script's body here.
 # Install FortiClient VPN
  Start-Process Msiexec.exe -Wait -ArgumentList '/i FortiClientVPN.msi REBOOT=ReallySuppress /qn'
 # ... 
 $PWD  # output the current location 
finally {
  # Restore the previous location.
  $prevPwd | Set-Location

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s