Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Windows 使用powershell中的CMD进程id(PID)将输入传递给CMD_Windows_Powershell_Cmd - Fatal编程技术网

Windows 使用powershell中的CMD进程id(PID)将输入传递给CMD

Windows 使用powershell中的CMD进程id(PID)将输入传递给CMD,windows,powershell,cmd,Windows,Powershell,Cmd,感谢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

感谢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
现在,我如何使用已经存在的CMD进程


换句话说,我想使用正在运行的cmd.exe进程的PID并将命令传递给它。

基于@Falcon的评论:

我想确定CMD是否作为系统运行

我认为代码应该可以工作,它可以检查作为系统运行的命令shell。对于作为系统运行的每个匹配shell,它将返回
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'
  }
}
上述代码需要在提升的shell中运行

代码基于正在提升的命令提示符的检查:

$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} } }

上述代码需要在非提升的PowerShell实例中运行。它正在测试是否缺少路径和句柄-对于提升的命令提示符,非提升的shell无法看到该路径和句柄。更改
eq'TEST'
条件以匹配您的窗口。

如果您允许我问一个明显的问题:如果您有PowerShell,为什么需要cmd?PowerShell不能为您做什么?@jeroenmoster-某些遗留程序在直接从PowerShell调用时实际上不能正确响应;这主要是因为PowerShell处理引用和参数传递的方式。不过,通常情况下,我会将命令写入批处理文件,然后使用
&“CMD/C$batchfilename”
调用它,而不是摆弄进程。请看这里。@JeffZeitlin:我之所以这样问,是因为我只能想到一些场景,在这些场景中,您希望与现有的cmd实例进行交互,但没有一个场景是这样做的。如果事实证明在这种情况下使用cmd是完全不必要的,那就更好了。@Jeroenmoster-我不确定我能想到任何我想要的场景,但我允许我可能。。。缺乏想象力的我很确定我可以想出一个相当简单的方法来获取CMD.EXE进程,但是如果有多个,我看不出有什么方法可以确定您可能需要哪一个。@Jeroenmoster-事实上,我将编写一个powershell脚本,检查系统上是否存在MS15-051权限提升漏洞。根据攻击行为,成功运行攻击后,将出现具有系统权限的CMD提示符。我想确定CMD是作为系统运行的,所以我决定将“whoami”传递给它。我还检查了CMD进程的SI(SessionID),但是尽管它作为系统运行,返回的SI是1。这就是所有的情况。你有更好的主意吗??谢谢