期待输出文件中的一行但获得更多

时间:2016-11-27 04:44:33

标签: powershell

我是Powershell的新手,我很难过。我试图从一些特定的顶级文件夹开始生成所有子目录中的文件列表,将结果输出到文本文件,或者更好的是CSV文件。例如,假设我有一个名为" TEST"的文件夹,它有一个名为" A"的子文件夹。每个文件夹都有一些文本文件。

我尝试过以下方法:

$path='c:\users\x\desktop\TEST'
$files=get-childitem $path -recurse
foreach($file in $files){
$file.fullname, $file.lastwritetime | out-file -append c:\users\x\desktop\output.txt
}

每个文件的结果输出分为两行,第一行是完整文件名&路径,第二个是日,月,年和时间。 我只是无法弄清楚如何让这两个属性出现在同一行:

c:\users\x\test\file1.txt, last modified date
c:\users\x\test\A\file2.txt, last modified date
:
etc.

我非常感谢解决这个问题的任何帮助。关于好的Powershell参考书的任何建议也将受到赞赏,因此我可以正确地学习这个主题。

我在Windows 7 Pro上使用Powershell。

1 个答案:

答案 0 :(得分:0)

关于这一行

$file.fullname, $file.lastwritetime | out-file -append c:\users\x\desktop\output.txt

当您使用逗号不在字符串中时,您正在使用数组表示法。这样做是将两个元素一次一个地发送到管道一个Out-File cmdlet。如果您在没有$file.fullname, $file.lastwritetime的情况下输入Out-File,您也会在控制台中看到两行。您可以通过将其设为字符串来解决此问题....

"$($file.fullname), $($file.lastwritetime)" | out-file -append c:\users\x\desktop\output.txt

但是,既然你试图制作一个CSV,我建议你看看Export-CSV。只需使用select-object即可获得所需的属性。

$path="c:\users\x\desktop\TEST"
$csv = "c:\users\x\desktop\output.txt"
Get-ChildItem $path -Recurse |
    Select-Object fullname,lastwritetime |
    Export-Csv -NoTypeInformation $csv