Switch user in PowerShell like "sudo su -" in Unix/Linux
You need to write a custom function for this. You could use the following function (below), and put it in your PowerShell Profile.
to use this, you have to use an elevated PowerShell Console.
As you can see, you have a $user
Parameter, which is set to adminsystem
by default (use your default username here). In ValidateSet()
you can say which values are allowed for the $user
Parameter.
it will then switch()
depending on your $user
parameter and read the correct username and password.
Then it will create a credential object, and a pssession as your desired user.
I do not recommend using Passwords as plain text in a script! You should follow this to store your Passwords safely in the script
function switch-psuser {
Param(
[Parameter(Position=0)]
[ValidateSet("adminsystem","administrator")]
$User = "adminsystem"
)
switch($User)
{
'adminsystem' { $username = "domain\adminsystem" ; $pw = "yyy"}
'administrator' { $username = "domain\administrator" ; $pw = "zzz" }
}
$password = $pw | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $username,$password
New-PSSession -Credential $cred | Enter-PSSession
}
Example Output:
PS C:\WINDOWS\system32> switch-psuser
[localhost]: PS C:\Users\adminsystem\Documents> whoami
domain\adminsystem
[localhost]: PS C:\Users\adminsystem\Documents> exit
PS C:\WINDOWS\system32> switch-psuser administrator
[localhost]: PS C:\Users\Administrator.DOMAIN\Documents> whoami
DOMAIN\administrator
[localhost]: PS C:\Users\Administrator.DOMAIN\Documents> exit
PS C:\WINDOWS\system32>
In this example you can see, when supplying no Value for $user
, it will take your default user. when supplying a username which is in ValidateSet()
and in switch()
it will take that one
hope that wasn't too complicated.otherwise just ask :)
SimonS' response is more convenient but I note that WhyWhat doesn't want to store the password in a file. You can instead use:
New-PSSession -Credential $cred | Enter-PSSession
Get-Credential, which is spawned when the PSCredential defined on -Credential is not defined, will ask for your username and password in a prompt instead. If you are using Windows Server Core Edition, this prompt is within the Powershell window. The credential is not vetted by your local computer in any way and you can use AD logins in the class Windows format DOMAIN\username
.