24/7/365 Support

Program: Start a Process As Another User in PowerShell

Discussion

If your script requires user credentials, you will want to store those credentials in a PowerShell PsCredential object. This lets you securely store those credentials, or pass them to other commands that accept PowerShell credentials. When you write a script that accepts credentials, consider letting the user to supply either a username or a preexisting credential. Example 164 demonstrates a useful approach that allows that. As the framework for this demonstration, the script lets you start a process as another user.

Example 164. StartProcessAsUser.ps1

############################################################################## ## ## StartProcessAsUser.ps1 ## ## Launch a process under alternate credentials, providing functionality ## similar to runas.exe. ## ## ie: ## ## PS >$file = JoinPath ([Environment]::GetFolderPath("System")) certmgr.msc ## PS >StartProcessAsUser Administrator mmc $file ## ## ## ##############################################################################

param( $credential = (GetCredential), [string] $process = $(throw "Please specify a process to start."), [string] $arguments = "" )

## Create a real credential if they supplied a username if($credential is "String") {

$credential = GetCredential $credential }

## Exit if they canceled out of the credential dialog if(not ($credential is "System.Management.Automation.PsCredential")) {

return }

## Prepare the startup information (including username and password) $startInfo = NewObject Diagnostics.ProcessStartInfo $startInfo.Filename = $process

Example 164. StartProcessAsUser.ps1 (continued)

$startInfo.Arguments = $arguments

## If we're launching as ourselves, set the "runas" verb if(($credential.Username eq "$ENV:Username") or ($credential.Username eq "\$ENV:Username")) {

$startInfo.Verb = "runas" } else {

$startInfo.UserName = $credential.Username $startInfo.Password = $credential.Password $startInfo.UseShellExecute = $false

}

## Start the process [Diagnostics.Process]::Start($startInfo)

Help Category:

Get Windows Dedicated Server

Only reading will not help you, you have to practice it! So get it now.

Processor RAM Storage Server Detail
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 128 GB (SSD SATA) Configure Server
Intel Atom C2750 2.4 GHz 8c/8t 8 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Xeon E3-1230 v2 3.3 GHz 4c/8t 16 GB DDR3 1× 256 GB (SSD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 250 GB (SSD SATA) Configure Server

What Our Clients Say