Switch user in PowerShell like "sudo su -" in Unix/Linux

1

0

When I am logged in to a Windows server as an Administrator in PowerShell, how do I switch to another user without a typing a password? I am looking for exactly the same feature as sudo su - or su in Linux.

pweruser

Posted 2018-11-01T16:05:31.793

Reputation: 11

1you would have to write a custom function, where you work with new-pssession and enter-pssession and already stored credentials, which you could switch depending on the user you want to be. – SimonS – 2018-11-01T16:11:16.553

Answers

2

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

Posted 2018-11-01T16:05:31.793

Reputation: 4 566

I don't want to store an admin password in a file. – WhyWhat – 2019-09-19T07:15:31.063

2

@WhyWhat There are lots of ways to not store your password in a file, at least not in plain text. e.g https://www.pdq.com/blog/secure-password-with-powershell-encrypting-credentials-part-2/

– SimonS – 2019-09-19T08:51:11.757