How to elevate an already running session within its own code

无人久伴 提交于 2019-12-06 08:41:13
Ansgar Wiechers

You can run cmdlets in another user's context when they allow providing explicit credentials (parameter -Credential), or by running them via Invoke-Command (which has a -Credential parameter).

Example:

$cred = Get-Credential
Invoke-Command -Computer $env:COMPUTERNAME -ScriptBlock {
  # commands here
} -Credential $cred

Or you could use something like this to re-run the entire script with different credentials:

if (-not $env:USERNAME -eq 'Me') {
  $cred  = Get-Credential
  $param = '-NoLogo', '-File', $MyInvocation.MyCommand.Path
  Start-Process "powershell.exe" -ArgumentList $param -Credential $cred
  exit $LASTEXITCODE
}

# other code here

Elevating the current session (or "moving" it to a different context) is not possible.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!