Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch current user using powershell?

my task is to create new windows local user, log in, using it and then do some actions. Creating new user wasn't a problem but i don't know how to switch current user to new one.

What i did is a piece of script which start new powershell window using new user:

$secpasswd = ConvertTo-SecureString $password -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ($config_name, $secpasswd)
Start-Process powershell.exe -Credential $mycreds -NoNewWindow

Is is possible to start doing rest of the script in this new window??

like image 992
Pafcio Avatar asked Apr 09 '13 07:04

Pafcio


People also ask

How do I change user in PowerShell?

When you start a PowerShell script, do it as here: Run PowerShell (or ps.exe) and add the script file with -file <script. ps1> as argument. Then, add the desired credentials by clicking the Change User or Group button.

How do I login as a different user in PowerShell?

Then you can right-click on the PowerShell icon, which shows you an option as Windows PowerShell. Hovering over that options, Click Shift and right-click together to open another menu. You can choose Run as Different User from the new menu. Then a different popup would be opened, as shown in the below image.

How do I switch between users in Windows 10 PowerShell?

Open Command Prompt or PowerShell in your Window 10 PC. Now, type in “tsdiscon” (without quotes) and press 'Enter'. The 'tsdiscon' command will take you to the lock screen. From there, you can go through the usual process to log into any user account on the PC.

How do I switch users in Command Prompt?

If you like command-line environments, open Command Prompt or PowerShell. Then, type tsdiscon and press Enter. The tsdiscon command takes you to the Lock screen. On it, click, tap, or press a key on your keyboard and then choose switch users.


Video Answer


1 Answers

Simple way is following:

  1. Create a script (let's call it init.ps1)
  2. Put in it all actions you want to invoke for user
  3. Add execute right to this script to $config_name
  4. Change your last line to (-noexit is just for debugging, without it powershell will close window after execution finish):

    Start-Process powershell.exe -Credential $mycreds -NoNewWindow -ArgumentList "-noexit -command FULL_PATH_TO_SCRIPT\init.ps1"

More difficult way is to install WinRM and use commands with Enter-PSSession (examples in the end of this link: http://technet.microsoft.com/en-us/library/hh849707.aspx)
like image 98
Piotr Stapp Avatar answered Sep 18 '22 20:09

Piotr Stapp