简体   繁体   English

在PowerShell中以管理员身份运行CMD

[英]Run CMD as admin in PowerShell

I hope this is simple. 我希望这很简单。

$cred = Get-Credential $env:USERDOMAIN\$env:USERNAME
$credUser = $cred.UserName
$credPW = $cred.Password

$Col1Row2 = New-Object System.Windows.Forms.Button
$Col1Row2.Location = New-Object System.Drawing.Size(5,80)
$Col1Row2.Size = New-Object System.Drawing.Size(150,25)
$Col1Row2.Text = "CMD as Admin"
$Col1Row2.Add_Click({Write-Host "Started Command Prompt.";$x= RunAs /user:$credUser C:\Windows\System32\cmd.exe })
$objForm.Controls.Add($Col1Row2)

There's a button to start command prompt inside my form, but I want it to start as admin by catching the user credentials at the beginning and using them to run. 我的表单中有一个用于启动命令提示符的按钮,但是我希望它以admin身份启动,方法是在开始时捕获用户凭据并使用它们来运行。 The problem is I can't seem to figure out how to get this to work. 问题是我似乎无法弄清楚如何使它工作。

If I run it in the script, it doesn't seem to work at all (in ISE). 如果我在脚本中运行它,则它似乎根本不起作用(在ISE中)。 If I run the line in PowerShell as RunAs /user:$credUser C:\\Windows\\System32\\cmd.exe it asks for the password. 如果我在PowerShell中以RunAs /user:$credUser C:\\Windows\\System32\\cmd.exe运行该行,则会要求输入密码。 If I run it with the password at the end it doesn't seem to care. 如果我使用密码结尾运行它,那似乎并不在乎。 Any assistance is appreciated. 任何帮助表示赞赏。

$params=@("/C";"$x";" >d:\\temp\\result.txt")

Parameters go here, change it to your parameters that you want to pass to Command Prompt. 参数在此处,将其更改为要传递给命令提示符的参数。

Start Process takes Credential Object hence suggesting this approach. 启动过程采用凭据对象,因此建议使用此方法。

$params=@("/C";"$x";" >d:\temp\result.txt")
$prog="cmd.exe"
Start-Process -Credential $cred  -Verb runas $prog +$params

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

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