【问题标题】:Powershell File search by date, display date and path info, cannot export CSVPowershell文件按日期搜索,显示日期和路径信息,无法导出CSV
【发布时间】:2019-01-28 20:00:50
【问题描述】:

我是 Powershell 的新手,我已经让我的批处理文件能够将结果输出到屏幕上。我希望将文件导出为 CSV,以便能够将其放入可按目录排序的 Excel 文件,然后按日期排序。

我可以使用Out-File 命令来编写基本文件,但 CSV 输出似乎无法正常工作。我只得到一个 CSV 文件,其中包含每条记录的 Length

有人可以帮忙吗?提前致谢。


这是我尝试过的:

#--Change the name with directory you want to visit --#    
$dir_to_look="E:\xPression\CustomerData\xPressionECR\*\XMLDATA"    

#--You may change the number of days of your choice --#   
$TwoDays=$(Get-Date).AddDays(-2)    

Remove-Item E:\xPression\CustomerData\xPressionECR\ReportOutput\Report.csv

#--Find the files which are modified or created within last 2 days --#    
Get-Childitem $dir_to_look *.xml  -Recurse | `   
        where-object {!($_.psiscontainer)} | `   
        where { $_.LastWriteTime -gt $TwoDays } | `   
        ForEach-Object {  "$($_.LastWriteTime) , $($_.Fullname)"| Out-File -LiteralPath E:\xPression\CustomerData\xPressionECR\ReportOutput\Report.csv -Append}

【问题讨论】:

  • 鉴于您使用$_.psiscontainer,我们可以假设您仅限于Powershell-v2吗?如果您将 Powershell-Version 添加为标签会有所帮助:)
  • 我的版本信息:PSVersion 4.0

标签: powershell csv powershell-4.0


【解决方案1】:

您应该仔细查看两个有用的函数:Select-ObjectExport-Csv

如果您要创建包含两行的 .csv 文件,其中包含 LastWriteTimeFullName,您可以这样做:

Get-Childitem $dir_to_look *.xml  -Recurse | Where-Object { $_.LastWriteTime -gt $TwoDays } | Select-Object LastWriteTime, FullName | Export-Csv -LiteralPath "E:\xPression\CustomerData\xPressionECR\ReportOutput\Report.csv "

【讨论】:

  • 非常感谢,这就像一个魅力。祝你有美好的一天!
  • @RDavidson 很高兴我能帮上忙!当答案对您有帮助时,您可以投票给其他人以证明他们很好。此外,当您的问题得到回答时,您可以将一个答案标记为正确,这样问题就不会显示为未决。参考。 (stackoverflow.com/help/someone-answers)
【解决方案2】:

您应该在管道末尾使用 Export-Csv 而不是 Out-File。您的代码将变为:

Get-Childitem $dir_to_look *.xml -Recurse  -File | 
where LastWriteTime -gt $TwoDays  | 
select Fullname, LastWriteTime |
Export-Csv -Path E:\xPression\CustomerData\xPressionECR\ReportOutput\Report.csv -NoTypeInformation

如果您在 Get-ChildItem 上使用 -File 参数,则无需测试 PSiContainer。您可以使用 select 传递您感兴趣的两个属性,然后输出到 csv 文件。您也不需要在第二个 where 语句末尾的管道符号后面加上 `。行尾的管道符号自动成为行继续标记。

希望这能回答您的问题。如果您对这段代码有任何其他疑问,我们很乐意跟进。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-01
    • 2018-11-19
    • 2014-06-19
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多