如何以特定用户身份执行Powershell cmdlet并将返回值保存在variables中?
我到目前为止是这个片段
Start-Process powershell.exe -Credential $credentials -NoNewWindow -ArgumentList "Get-Item Env:AppData"
问题是,任何返回值只能在进程中生效,并不会从我执行所述命令的位置进入PowerShell环境。
您可以使用具有指定凭据的Invoke-Command ,然后从调用的ScriptBlock中return值:
$Credentials = (Get-Credential) $ScriptToExecute = {return (Get-Item Env:AppData)} $AppData = Invoke-Command -ComputerName localhost -Credential $Credentials -ScriptBlock $ScriptToExecute $AppData # Now contains the Environment var named "AppData"
如果这会引发任何错误,则需要执行winrm quickconfig 。 如果仍然失败,请以pipe理员权限运行powershell.exe。