如何在自己的代码中提升已经 运行 的会话
How to elevate an already running session within its own code
我正在编写一个 PowerShell 脚本来配置 Active Directory 中的一些东西。
我需要运行它作为一个特定的用户才能获得进程的正确权限,目前我运行通过.ps1文件。 bat 文件,所以我可以选择 "run as a different user" 或 "run as administrator".
我想要实现的是,在脚本中我会要求用户提供正确的凭据,然后使用输入的用户凭据将会话提升到 运行。
我试过在我的代码中使用它:
Start-Process powershell.exe -Credential "TestDomain\Me"
但它只是打开一个空的 PS 会话,而当前会话保持 运行ning。
我想使用此代码从用户处获取积分:
$msg = "Enter your Domain Admin Credentials";
$creds = $Host.UI.PromptForCredential($caption,$msg,"","")
$rstusername = $creds.username;
$rstpassword = $creds.GetNetworkCredential().password
然后使用 $rstusername
和 $rstpassword
来更改 运行ning 脚本凭据。
这可能吗?
您可以 运行 在其他用户的上下文中允许提供显式凭据(参数 -Credential
)的 cmdlet,或者通过 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
无法提升当前会话(或"moving"它到不同的上下文)。
我正在编写一个 PowerShell 脚本来配置 Active Directory 中的一些东西。
我需要运行它作为一个特定的用户才能获得进程的正确权限,目前我运行通过.ps1文件。 bat 文件,所以我可以选择 "run as a different user" 或 "run as administrator".
我想要实现的是,在脚本中我会要求用户提供正确的凭据,然后使用输入的用户凭据将会话提升到 运行。
我试过在我的代码中使用它:
Start-Process powershell.exe -Credential "TestDomain\Me"
但它只是打开一个空的 PS 会话,而当前会话保持 运行ning。
我想使用此代码从用户处获取积分:
$msg = "Enter your Domain Admin Credentials";
$creds = $Host.UI.PromptForCredential($caption,$msg,"","")
$rstusername = $creds.username;
$rstpassword = $creds.GetNetworkCredential().password
然后使用 $rstusername
和 $rstpassword
来更改 运行ning 脚本凭据。
这可能吗?
您可以 运行 在其他用户的上下文中允许提供显式凭据(参数 -Credential
)的 cmdlet,或者通过 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
无法提升当前会话(或"moving"它到不同的上下文)。