【问题标题】:Output from Get-Content and File Path获取内容和文件路径的输出
【发布时间】:2017-07-06 03:28:37
【问题描述】:

我在一个文件夹中有一组.txt 文件。例如:

1.txt
2.txt
3.txt

这些文件名后面包含一个日期。例如,1.txt 可能包含:

06/11/2017 randomdocument.txt
06/12/2017 otherdocument.txt
07/11/2017 yadocument.txt
01/02/2017 randomdocument.txt

我想:

  • 获取与特定日期正则表达式模式匹配的行
  • 将该行及其所在文件的路径写入新文档。

我的代码是第一部分。我已经尝试了各种迭代,第二部分没有雪茄。任何帮助将不胜感激。


代码

Set-Location c:\users\john.smith\desktop\FORREPORT
$files = Get-ChildItem -recurse
$SearchPattern = "0[5,6]{1}/[0-9]\w{1,2}/2017"

Foreach ($file in $files) {
  $line = Get-ChildItem -recurse | Get-Content | Select-String $SearchPattern
  $d = $line | Select-Object file.FullName 
  $d | Add-Content -path c:\users\john.smith\desktop\ohsnap.txt

}

所需的输出:

 06/12/2017 randomdocument.txt in c:\users\john.smith\desktop\FORREPORT\1.txt

【问题讨论】:

  • 您是说要选择在特定范围内具有LastWriteTime 属性的文件吗?
  • 你的段落很难理解,但是gci c:\users\john.smith\desktop\FORREPORT -Recurse -pv File| select-string '0[5,6]{1}/[0-9]\w{1,2}/2017' | select Line, @{N='filename';E={$File.FullName}} ?
  • 您好 Bill,是的,他们是 LastWriteTime,但报告已经存在。因此,换句话说,我运行了 3 个不同的 .txt 文件,它们包含驻留在三个单独文件夹中的文档的 LastWriteTime。我正在尝试找到一种方法来找到满足特定日期条件的这 3 个 .txt 文件中的所有行项目(我完成了此操作),然后将它们编译到提供行项目路径的新报告中以及每个行项目来自三个 .txt 文件中的哪一个。前任。 06/12/2017 Bobburgers.docx 位于 c:\users\john.smith\desktop\FORREPORTS\1.txt
  • TessellatingHeckler。谢谢你。我知道。我的段落非常可怕;但是,我想不出办法来澄清。
  • @user7431743 我根据您的要求进行了编辑。请让我知道它是否正确。

标签: powershell


【解决方案1】:

对代码的改动很小:

Set-Location c:\users\john.smith\desktop\FORREPORT

$files = Get-ChildItem -recurse
$SearchPattern = "0[5,6]{1}/[0-9]\w{1,2}/2017"

Foreach ($file in $files) {
  $lines =  Get-Content $file | Select-String $SearchPattern
  if($lines){
      foreach($line in $lines){
        "$line`t$($file.FullName)" | Add-Content -path c:\users\john.smith\desktop\ohsnap.txt
      }
  }
}

这会在新文档的新行上打印每一行。如果您希望所有匹配的行都在一行,请删除 foreach:

Set-Location c:\users\john.smith\desktop\FORREPORT

$files = Get-ChildItem -recurse
$SearchPattern = "0[5,6]{1}/[0-9]\w{1,2}/2017"

Foreach ($file in $files) {
  $lines =  Get-Content $file | Select-String $SearchPattern
  if($lines){
        "$lines`t$($file.FullName)" | Add-Content -path c:\users\john.smith\desktop\ohsnap.txt
  }
}

if 还将检查是否确实找到了匹配的行,这样您就不会得到 $file.Fullname 的输出,而 $lines 为空。

PS 您的问题和代码是我能想到的使用this quote 的最佳示例。注意! ;-p

【讨论】:

  • 是的!谢谢gmsOulman。这行得通!另外,我会注意这一点。我是自学成才的,所以我错过了很多我可能会通过正式培训获得的形式,
猜你喜欢
  • 1970-01-01
  • 2013-04-11
  • 1970-01-01
  • 2019-05-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-01
  • 1970-01-01
  • 2012-10-20
相关资源
最近更新 更多