简体   繁体   English

Powershell Out-File无法按预期使用反向字符串

[英]Powershell Out-File not working as expected with a reversed string

I need to write a file backwards line by line to another file. 我需要逐行向后写一个文件到另一个文件。 I can get it to work fine in the PowerShell window, but when I try to pipe it to an Out-File , it doesn't work. 我可以在PowerShell窗口中使它工作正常,但是当我尝试将其传递给Out-File ,它不起作用。 This is my script: 这是我的脚本:

Get-Content C:\Users\Administrator\Desktop\files.txt | ForEach-Object {
    $text = $_.toCharArray()
    [Array]::Reverse($text)
    -join $text | Out-File 'C:\Users\Administrator\Desktop\reversed.txt'
}

This actually creates a file on the Desktop, but doesn't give it any content. 这实际上在桌面上创建了一个文件,但没有给它任何内容。

If I simply don't pipe to Out-File on the last line, it works fine, and prints the reversed file straight to the PowerShell window. 如果我只是在最后一行没有管道Out-File ,它可以正常工作,并将反转的文件直接打印到PowerShell窗口。

I have tried it with and without the single quotes, as well as using the -FilePath option. 我已尝试使用和不使用单引号,以及使用-FilePath选项。 Nothing's working. 没有什么工作。 Any ideas out there? 有什么想法吗?

Since the -Append parameter is not used, Out-File will overwrite the file each time it processes a line from the source file. 由于未使用-Append参数,因此Out-File将在每次处理源文件中的行时覆盖该文件。 I suspect the last line of the source file is an empty line which is why you see nothing in the output file. 我怀疑源文件的最后一行是一个空行,这就是为什么你在输出文件中看不到任何内容。

The proper way to do this is as @TheMadTechnician suggests: 正确的方法是@TheMadTechnician建议:

Get-Content C:\Users\Administrator\Desktop\files.txt | 
    ForEach-Object {
        $text = $_.toCharArray()
        [Array]::Reverse($text)
        -join $text
    } | 
    Out-File C:\Users\Administrator\Desktop\reversed.txt

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

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