如何在PowerShell中捕获外部命令的文件输出到变量而非生成文件?
在PowerShell中捕获外部命令的文件输出到变量(不生成实际文件)
方法1:利用命名管道实现无文件捕获
Windows系统支持命名管道,可让外部命令将输出写入管道,再由PowerShell从管道读取内容,全程不生成实体文件。
具体步骤:
- 创建命名管道:
$pipePath = "\\.\pipe\TempOutputPipe" New-Item -Path $pipePath -ItemType Pipe | Out-Null
- 启动后台作业读取管道内容:
$readJob = Start-Job -ScriptBlock { $pipe = New-Object System.IO.Pipes.NamedPipeClientStream(".", $args[0], [System.IO.Pipes.PipeDirection]::In) $pipe.Connect() $streamReader = New-Object System.IO.StreamReader($pipe) $outputContent = $streamReader.ReadToEnd() $streamReader.Close() $pipe.Close() return $outputContent } -ArgumentList $pipePath
- 调用外部命令,将管道路径作为输出参数传入:
& "C:\mycommand.exe" $pipePath
- 读取作业结果并清理管道:
$test = Receive-Job $readJob -Wait -AutoRemoveJob Remove-Item $pipePath -Force
执行后,$test变量就会存储外部命令输出的CSV内容。
方法2:临时文件方案(管道不可用时备选)
如果外部命令仅支持写入实际文件路径,可使用临时文件中转,读取后立即删除:
$tempFilePath = [System.IO.Path]::GetTempFileName() & "C:\mycommand.exe" $tempFilePath $test = Get-Content $tempFilePath -Raw Remove-Item $tempFilePath -Force
此方案会短暂生成临时文件,但能满足捕获需求。
注意事项
- 部分外部命令可能不识别命名管道路径,仅接受真实文件路径,此时只能选用临时文件方案。
- 命名管道操作需确保读取逻辑正确,避免出现进程阻塞问题。
内容的提问来源于stack exchange,提问作者astidham2003
相关产品推荐
相关产品推荐

