[英]Pass input to CMD, using CMD process id (PID) in powershell
Thanks to Abbas, the following code enable us to call a cmd process and pass command to it using PowerShell script. 多亏了Abbas,以下代码使我们能够调用cmd进程,并使用PowerShell脚本将命令传递给该进程。
$psi = New-Object System.Diagnostics.ProcessStartInfo;
$psi.FileName = "cmd.exe"; #process file
$psi.UseShellExecute = $false; #start the process from it's own executable file
$psi.RedirectStandardInput = $true; #enable the process to read from standard input
$p = [System.Diagnostics.Process]::Start($psi);
Start-Sleep -s 2 #wait 2 seconds so that the process can be up and running
$p.StandardInput.WriteLine("dir"); #StandardInput property of the Process is a .NET StreamWriter object
Now, How can I use a CMD process that already exists. 现在,我如何使用已经存在的CMD进程。
In better words, I want to use the PID of a cmd.exe process that is running and pass the command to it. 用更好的话来说,我想使用正在运行的cmd.exe进程的PID并将命令传递给它。
Based on @Falcon's comment: 基于@Falcon的评论:
I want to be sure that the CMD is running as SYSTEM
我想确保CMD作为SYSTEM运行
I think the code should work, which checks for a command shell running as SYSTEM. 我认为代码应该可以正常工作,该代码可以检查作为SYSTEM运行的命令外壳。 It will return
true
for each matching shell that's running as SYSTEM, with title=TEST: 对于每个以SYSTEM = SYSTEM运行的匹配外壳程序,它将返回
true
,其中title = TEST:
Get-CimInstance Win32_Process -Filter "name = 'cmd.exe'" | ForEach-Object {
if ((Get-Process -Id $_.ProcessId).MainWindowTitle -eq 'TEST') {
(Invoke-CimMethod -InputObject $_ -MethodName GetOwner).User -eq 'SYSTEM'
}
}
The above code needs running in an elevated shell 上面的代码需要在高架外壳中运行
The code based on this article checks for the command prompt being elevated: 基于本文的代码检查命令提示符是否升高:
$p = Get-Process -Name cmd | where {$_.MainWindowTitle -eq 'TEST'} |
Select Name, @{Name="Elevated"; Expression={ if ($this.Name -notin @('Idle','System')) {-not $this.Path -and -not $this.Handle} } }
The code above needs running in a non-elevated PowerShell instance . 上面的代码需要在非高架PowerShell实例中运行 。 It is testing for the absence of a path & handle - which the non-elevated shell can't see for an elevated command prompt.
它正在测试是否缺少路径和句柄-非升高的外壳看不到升高的命令提示符。 Change the
eq 'TEST'
condition to match your window. 更改
eq 'TEST'
条件以匹配您的窗口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.