Home > other >  How to exit shell when the script contains restarting a new instance?
How to exit shell when the script contains restarting a new instance?

Time:10-20

At the beginning of my script, I add a piece of code to make sure the shell run with full admin privileges:

# Running with full admin privileges
param([switch]$Elevated)

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

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

# Other stuff below...

After that is a normal script (the Other stuff below section). The problem is, I want to automatically close the shell window after the script is done. Before I add the full privilege code, putting exit in the bottom of the script works fine, but not now anymore. I don't understand why, because everything else in this section works fine.

CodePudding user response:

Normally scripts auto exit at the end. Try to omit -noexit parameter from argumentlist and delete exit at the bottom of the script. For me, there is no sense to call a script with -noexit and put exit at the end of it. Without these all will automagically work.

If you want to examine what is going on during script writing, you can put eg. a timeout /t 90 command at the end, so you get 90 seconds to examine output before it auto closes.

  • Related