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)