How to start a new instance of powershell and run commands in it?

This is what I am trying to accomplish:

I need the user to automatically run the powershell script when he logs into the computer, the script launches the Powershell Promoted link (just as if the user could click Run Runshell as Administrator), and then he runs some commands in a new Powershell object, and then closes a new Powershell object.

This function will now create and run a new Powershell object in elevated mode.

function Set-Elevation
{
   # Create a new process object that starts PowerShell
   $newProcess = New-Object System.Diagnostics.ProcessStartInfo "powershell";
   # Indicate that the process should be elevated
   $newProcess.Verb = "runas";
   # Start the new process
   [System.Diagnostics.Process]::Start($newProcess) | Out-Null
}

However, how do I get him to run new teams? And how can I close the object later?

Any syntax tips would be appreciated.

+4
source share
2 answers

Start-Process:

function IsAdministrator
{
    $Identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
    $Principal = New-Object System.Security.Principal.WindowsPrincipal($Identity)
    $Principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
}

function IsUacEnabled
{
    (Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System).EnableLua -ne 0
}

#
# Main script
#
if (!(IsAdministrator))
{
    if (IsUacEnabled)
    {
        [string[]]$argList = @('-NoProfile', '-NoExit', '-File', $MyInvocation.MyCommand.Path)
        $argList += $MyInvocation.BoundParameters.GetEnumerator() | Foreach {"-$($_.Key)", "$($_.Value)"}
        $argList += $MyInvocation.UnboundArguments
        Start-Process PowerShell.exe -Verb Runas -WorkingDirectory $pwd -ArgumentList $argList 
        return
    }
    else
    {
        # Log an error, do nothing or Start-Process -Credentials <admin_creds>
    }
}
+4

script, PS1 - .

$WID=[System.Security.Principal.WindowsIdentity]::GetCurrent();
$WIP=new-object System.Security.Principal.WindowsPrincipal($WID);
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator;
If ($WIP.IsInRole($adminRole)){
}else {
  $newProcess = new-object System.Diagnostics.ProcessStartInfo 'PowerShell';
  $newProcess.Arguments = $myInvocation.MyCommand.Definition
  $newProcess.Verb = 'runas'
  [System.Diagnostics.Process]::Start($newProcess);Write-Host 'Prompting for Elevation'
  exit
}

Write-Host 'ElevatedCodeRunsHere';
Write-Host 'Press any key to continue...'
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
+2