繁体   English   中英

如何使用 Powershell 以不同用户身份运行 Command?

[英]How to run Command as a different user with Powershell?

我正在尝试制作一个脚本来更改给定 dns 记录的 HostnameAlias。

但是只有某些用户有权编辑这些记录,例如ADMIN可以编辑它而CURRENTUSER不能。

目前我有这段代码:

param(
    [ValidateNotNull()]
    [System.Management.Automation.PSCredential]
    $Credential = $(Get-Credential)
)
$Command = "Set-DnsServerResourceRecord -NewInputObject $($NewObject) -OldInputObject $($OldObject) -ZoneName $($ZoneName)"
Start-Process -FilePath PowerShell -NoNewWindow -Credential $Credential -ArgumentList $Command

但我只是不断收到Start-Process : This command cannot be run due to the error: The user name or password is incorrect即使我绝对确定它们确实正确。

我在这里做错了什么。

Ps,我已经查看了所有相关问题,似乎没有人回答我的问题。

您可以调用System.Management.Automation.PSCredential对象来指定您想要的任何凭据并在任何进程中使用它运行

$User = 'yourdomain\youruser'
$Password = 'yourpassword'

$Secure_Password = ConvertTo-SecureString $Password -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential($User, $Secure_Password)


$Command = "Set-DnsServerResourceRecord -NewInputObject $($NewObject) -OldInputObject $($OldObject) -ZoneName $($ZoneName)"
Start-Process -FilePath PowerShell -NoNewWindow -Credential $Credential -ArgumentList $Command

你可以使用这个:

#Get User credential
$Credential = Get-Credential Domain\UserNameYouWant

#Use System.Diagnostics to start the process as User
$ProcessInfo = New-Object System.Diagnostics.ProcessStartInfo
#With FileName we're basically telling powershell to run another powershell process
$ProcessInfo.FileName = "powershell.exe"
#CreateNoWindow helps avoiding a second window to appear whilst the process runs
$ProcessInfo.CreateNoWindow = $true
#Note the line below contains the Working Directory where the script will start from
$ProcessInfo.WorkingDirectory = $env:windir
$ProcessInfo.RedirectStandardError = $true 
$ProcessInfo.RedirectStandardOutput = $true 
$ProcessInfo.UseShellExecute = $false
#The line below is basically the command you want to run and it's passed as text, as an argument
$ProcessInfo.Arguments = "The command you want"
#The next 3 lines are the credential for User as you can see, we can't just pass $Credential
$ProcessInfo.Username = $Credential.GetNetworkCredential().username
$ProcessInfo.Domain = $Credential.GetNetworkCredential().Domain
$ProcessInfo.Password = $Credential.Password
#Finally start the process and wait for it to finish
$Process = New-Object System.Diagnostics.Process 
$Process.StartInfo = $ProcessInfo 
$Process.Start() | Out-Null 
$Process.WaitForExit() 
#Grab the output
$GetProcessResult = $Process.StandardOutput.ReadToEnd()
# Print the Job results
$GetProcessResult

只是我的一个错误,在输入凭据时忘记在用户名之前指定域。

可以这样解决Get-Credential Domain\\

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM