4

我正在使用以下命令将目录的内容输出到 txt 文件:

$SearchPath="c:\searchpath"
$Outpath="c:\outpath"

Get-ChildItem "$SearchPath" -Recurse | where {!$_.psiscontainer} | Format-Wide -Column 1'
| Out-File "$OutPath\Contents.txt" -Encoding ASCII -Width 200

当我这样做时,我最终得到的是一个包含我需要的信息的 txt 文件,但它添加了许多我不需要的回车,使输出更难阅读。

这是它的样子:

    c:\searchpath\directory

name of file.txt

name of another file.txt


    c:\searchpath\another directory

name of some file.txt

这使得 txt 文件需要大量滚动,但实际信息并不多,通常不到一百行。

我希望它看起来像:

  c:\searchpath\directory
nameoffile.txt
  c:\searchpath\another directory
another file.txt

这是我到目前为止尝试过的,没有用

$configFiles=get-childitem "c:\outpath\*.txt" -rec
foreach ($file in $configFiles)
{
(Get-Content $file.PSPath) | 
Foreach-Object {$_ -replace "'n", ""} | 
Set-Content $file.PSPath
}

我也试过 'r 但两个选项都保持文件不变。

另一种尝试:

Select-String -Pattern "\w" -Path 'c:\outpath\contents.txt' | foreach {$_.line}'
| Set-Content -Path c:\outpath\contents2.txt

当我在末尾没有 Set-content 的情况下运行该字符串时,它在 ISE 中完全符合我的需要,但是一旦我在末尾添加 Set-Content,它就会再次在我不需要的地方回车他们。

这里有一些有趣的事情,如果我创建一个带有几个回车符和几个制表符的文本文件,那么如果我使用我一直在使用的相同 -replace 脚本,但在 txt 文件中使用t to replace the tabs, it works perfect. Butr 和r 以及 `n 然后运行n do not work. It's almost as though it doesn't recognize them as escape characters. But if I add脚本,它仍然没有取代任何东西。似乎不知道该怎么处理它。

4

3 回答 3

4

Set-Content默认添加换行符。在您最后一次尝试中替换Set-Content为您的问题将为您提供所需的文件:Out-File

Select-String -Pattern "\w" -Path 'c:\outpath\contents.txt' | foreach {$_.line} | 
Out-File -FilePath c:\outpath\contents2.txt
于 2012-05-26T08:54:35.570 回答
1

这不是'r(撇号),而是一个反引号:`r。这是美式键盘布局中 tab 键上方的键。:)

于 2012-05-25T18:09:15.610 回答
1

您可以使用以下方法简单地避免所有这些空行Select-Object -ExpandProperty Name

Get-ChildItem "$SearchPath" -Recurse | 
    Where { !$_.PSIsContainer } |
    Select-Object -ExpandProperty Name | 
    Out-File "$OutPath\Contents.txt" -Encoding ASCII -Width 200

...如果您不需要文件夹名称。

于 2012-05-25T18:21:42.870 回答