powershell - 如何在自己的代码中提升已经运行的 session

标签 powershell batch-file active-directory powershell-4.0 elevation

我正在编写一个 PowerShell 脚本来配置 Active Directory 中的一些内容。

我需要以特定用户身份运行它,以便获得进程的正确权限,目前我正在通过 .bat 文件运行 .ps1 文件,因此我可以选择“以不同用户身份运行”或“以管理员身份运行”。

我想要实现的是,在脚本中我会要求用户提供正确的凭据,然后提升 session 以使用输入的用户凭据运行。

我试过在我的代码中使用它:

Start-Process powershell.exe -Credential "TestDomain\Me"

但它只是打开一个空的 PS session ,而当前 session 继续运行。

我想使用这段代码从用户那里获取信用:

$msg = "Enter your Domain Admin Credentials"; 
$creds = $Host.UI.PromptForCredential($caption,$msg,"","")
$rstusername = $creds.username;    
$rstpassword = $creds.GetNetworkCredential().password 

然后使用 $rstusername$rstpassword 来更改运行脚本的凭据。

这可能吗?

最佳答案

当 cmdlet 允许提供显式凭据(参数 -Credential)时,您可以在其他用户的上下文中运行它们,或者通过 Invoke-Command(具有 -Credential 参数)。

例子:

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

或者您可以使用类似这样的方法以不同的凭据重新运行整个脚本:

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

提升当前 session (或将其“移动”到不同的上下文)是不可能的。

关于powershell - 如何在自己的代码中提升已经运行的 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32370223/

相关文章:

powershell - 在 powershell 中使用 WinRM 成功配置和监听

powershell - 在不使用Get-content的情况下将变量转换为字节

batch-file - 需要帮助编写批处理文件以将多个文件处理成逗号分隔的文本文件

powershell - 递归添加文件到文件夹,如果不存在则创建文件夹

powershell - 管理员权限的通用测试

Azure Active Directory 登录 : Web App Permissions, 未触发用户同意

powershell - 尝试使用 PowerShell 脚本从 Active Directory 中的所有组中删除用户

c# - 从 Active Directory 获取用户名

batch-file - ffmpeg 在尝试处理之前检查文件是否存在

batch-file - 通过将文件拖放到批处理文件上来打开文件