How to switch current user using powershell?
Asked Answered
Q

1

7

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??

Quarles answered 9/4, 2013 at 7:29 Comment(1)
$config_name is actually the usernameSucy
R
5

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)
Redfaced answered 9/4, 2013 at 18:23 Comment(2)
"3. Add execute right to this script to $config_name" ::: where is this done? I don't see $config_name mentioned anywhere.Lorrielorrimer
Why didn't you flesh out init.ps1 ? Isn't that what we need to know to switch user? Also why wouldn't you point out how to pass creds?Packer

© 2022 - 2024 — McMap. All rights reserved.