Dav*_*ony 2 powershell elevation batch-file active-directory powershell-4.0
我正在编写一个可在Active Directory中配置某些功能的PowerShell脚本。
我需要以特定用户身份运行它,以便获得该过程的正确权限,目前我正在通过.bat文件运行.ps1文件,因此我可以选择“以其他用户身份运行”或“以管理员”。
我要实现的目标是,在脚本中,我将向用户询问正确的凭据,然后根据输入的用户凭据提升会话运行速度。
我尝试在我的代码中使用它:
Start-Process powershell.exe -Credential "TestDomain\Me"
Run Code Online (Sandbox Code Playgroud)
但是它只是在当前会话继续运行的同时打开一个空的PS会话。
我想使用此代码来获得用户的信任:
$msg = "Enter your Domain Admin Credentials";
$creds = $Host.UI.PromptForCredential($caption,$msg,"","")
$rstusername = $creds.username;
$rstpassword = $creds.GetNetworkCredential().password
Run Code Online (Sandbox Code Playgroud)
然后使用$rstusernameAND $rstpassword来更改正在运行的脚本凭据。
那有可能吗?
当cmdlet允许提供显式凭据(参数-Credential)时,可以在其他用户的上下文中运行它们Invoke-Command,也可以通过(具有-Credential参数的)运行cmdlet 。
例:
$cred = Get-Credential
Invoke-Command -Computer $env:COMPUTERNAME -ScriptBlock {
# commands here
} -Credential $cred
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用类似的方法使用不同的凭据重新运行整个脚本:
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
Run Code Online (Sandbox Code Playgroud)
无法提升当前会话(或将其“移动”到其他上下文)。
| 归档时间: |
|
| 查看次数: |
5954 次 |
| 最近记录: |