Powershell:你如何阅读&在一个管道内写入I / O? [英] Powershell: how do you read & write I/O within one pipeline?

查看:93
本文介绍了Powershell:你如何阅读&在一个管道内写入I / O?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够输入快速,简单的命令,就地操作文件。例如:

 #prettify一个XML文件
format-xml foo | out-file foo

这是行不通的,因为管道设计为贪婪。只要上游cmdlet处理第一行输入,下游cmdlet就会获得一个写入锁定,这会阻止上游cmdlet读取文件的其余部分。



有许多可能的解决方法:写入临时文件,将操作分成多个流水线(将中间结果存储在变量中)等。但我认为这是一个非常普遍的任务,有人开发了一个快速,shell友好的捷径。

我试过这个:

 函数缓冲区对象
{
[CmdletBinding()]
param(
[parameter(Mandatory = $ True ,ValueFromPipeline = $ True)]
[psobject] $ InputObject


egin {$ buf = new-list psobject}
process {$ buf.Add $ InputObject)}
end {$ buf}
}
format-xml foo |缓冲区对象| out-file foo

在某些情况下,它可以正常工作。映射到一个简短的别名,并成为一个普通的分布,如PSCX,这将是足够好的快速交互式任务。不幸的是,一些cmdlet(包括out-file)在他们的Begin {}方法中而不是在Process {}中获取锁,所以它不能解决这个特殊的例子。

<其他想法?

解决方案

据我记忆(现在无法测试),您可以读取整个文件内存与命名空间符号:

  $ {c:file1.txt} = $ {c:file1.txt} -replace ao


I'd like to be able to type quick, simple commands that manipulate files in-place. For example:

# prettify an XML file
format-xml foo | out-file foo

This won't work because the pipeline is designed to be "greedy." The downstream cmdlet acquires a Write lock to the file as soon as the upstream cmdlet processes the first line of input, which stalls the upstream cmdlet from reading the rest of the file.

There are many possible workarounds: write to temporary files, separate operations into multiple pipelines (storing intermediate results in variables), or similar. But I figure this is a really common task for which someone has developed a quick, shell-friendly shortcut.

I tried this:

function Buffer-Object 
{
    [CmdletBinding()]
    param (
        [parameter(Mandatory=$True, ValueFromPipeline=$True)]
        [psobject] $InputObject
    )

    begin { $buf = new-list psobject }
    process { $buf.Add($InputObject) }
    end { $buf }
}
format-xml foo | buffer-object | out-file foo

It works ok in some situations. Mapped to a short alias and rolled into a common distribution like PSCX, it would be "good enough" for quick interactive tasks. Unfortunately it appears that some cmdlets (including out-file) grab the lock in their Begin{} method rather than in Process{}, so it does not solve this particular example.

Other ideas?

解决方案

As far as I remember (can't test now), you can read a whole file into memory with the namespace notation:

${c:file1.txt} = ${c:file1.txt} -replace "a" "o"

这篇关于Powershell:你如何阅读&amp;在一个管道内写入I / O?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆