【问题标题】:How to name each Out-File like each input line from Get-Content?如何像 Get-Content 中的每个输入行一样命名每个 Out-File?
【发布时间】:2019-03-31 15:14:23
【问题描述】:

我想从pathlist.txt中的每个路径获取内容,每个路径内容都应该保存到他自己的pathname.txt文件中,命名为输入路径。

所以是这样的:


$pathlist = Get-Content C:\Test\pathlist.txt

$pathlist | % { 
  Get-ChildItem $_ -Recurse |
    Out-File C:\Test\Output\"computername_" + $($_.replace("\","_").replace(":","")) +".txt" 
}

输入:

  • C:\Test\Test\Test
  • D:\下载
  • C:\Windows\Temp

输出:

  • 计算机名_C_Test_Test_Test.txt
  • 计算机名_D_Download.txt
  • 计算机名_C_Windows_Temp.txt

每个输出文本文件都包含来自 Get-ChildItem -Recurse 命名路径的结果。

【问题讨论】:

    标签: powershell


    【解决方案1】:
    $pathlist = Get-Content ‪C:\Test\pathlist.txt
    
    $pathlist | ForEach-Object { 
      $outFile = 'C:\Test\Output\computername_{0}.txt' -f $_ -replace ':?\\', '_'
      Get-ChildItem -LiteralPath $_ -Recurse -Name > $outFile
    }
    
    • 我已将多个 .Replace() 方法调用替换为对 PowerShell's -replace operator 的单个基于正则表达式的调用。

    • 我已将字符串连接 (+) 替换为对 PowerShell's format operator-f 的一次调用。

    • 为简洁起见,我已将 Out-File 替换为 >

    • 我已将-Name 添加到Get-ChildItem 调用中,以便输出相对于输入路径的路径字符串;如果您想要绝对路径,请改用
      (Get-ChildItem -LiteralPath $_ -Recurse).FullName > $outFile(或
      Get-ChildItem -LiteralPath $_ -Recurse | Select-Object -ExpandProperty FullName > $outFile)。

    至于你尝试了什么

    您的问题是 您没有在 (...) 中包装通过字符串连接构建目标文件名的 表达式,如果您想使用表达式作为命令参数

    请注意:

    • 在表达式中,必须(完全)引用字符串文字
    • $(...) 仅在需要包装多个语句时才需要;否则,如果需要覆盖标准 operator precedence,请使用 (...)

    因此,您的原始命令可以通过以下方式修复:

    ... | Out-File ('C:\Test\Output\computername_' + $_.replace("\","_").replace(":","") + '.txt')
    

    【讨论】:

    • 很高兴听到这个消息,@matze;我的荣幸。
    【解决方案2】:

    似乎一切正常,但存在拼写问题。试试这个:

    $pathlist | ForEach { Get-ChildItem -path $_ -Recurse | Out-File "C:\Test\Output\computername_" + $($_.replace("\","_").replace(":","")) +".txt" }
    

    然后告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-28
      • 1970-01-01
      • 2020-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-22
      相关资源
      最近更新 更多