windows 如何使用powershell切换当前用户?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15895877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 10:25:15  来源:igfitidea点击:

How to switch current user using powershell?

windowspowershellswitch-user

提问by Pafcio

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.

我的任务是创建新的 Windows 本地用户,登录,使用它,然后执行一些操作。创建新用户不是问题,但我不知道如何将当前用户切换到新用户。

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

我所做的是一段脚本,它使用新用户启动新的 powershell 窗口:

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

是否可以在这个新窗口中开始执行脚本的其余部分?

回答by Piotr Stapp

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"

  1. 创建一个脚本(我们称之为 init.ps1)
  2. 将您要为用户调用的所有操作放入其中
  3. 将此脚本的执行权限添加到 $config_name
  4. 将最后一行更改为(-noexit 仅用于调试,否则powershell 将在执行完成后关闭窗口):

    启动进程 powershell.exe -Credential $mycreds -NoNewWindow -ArgumentList "-noexit -command FULL_PATH_TO_SCRIPT\init.ps1"

更困难的方法是安装 WinRM 并使用带有 Enter-PSSession 的命令(此链接末尾的示例: http://technet.microsoft.com/en-us/library/hh849707.aspxhttp://technet.microsoft.com/en-us/library/hh849707.aspx