Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell 如何将每个输出文件命名为Get Content中的每个输入行?_Powershell - Fatal编程技术网

Powershell 如何将每个输出文件命名为Get Content中的每个输入行?

Powershell 如何将每个输出文件命名为Get Content中的每个输入行?,powershell,Powershell,我想从pathlist.txt中的每个路径获取内容,每个路径内容都应该保存到自己的pathname.txt文件中,名称与输入路径类似 比如说: $pathlist = Get-Content C:\Test\pathlist.txt $pathlist | % { Get-ChildItem $_ -Recurse | Out-File C:\Test\Output\"computername_" + $($_.replace("\","_").replace(":",""))

我想从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
输出:

  • computername\u C\u Test\u Test.txt
  • computername_D_Download.txt
  • computername\u C\u Windows\u Temp.txt

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

看起来一切正常,但存在拼写问题。试试这个:

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

$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()
    方法调用替换为对的单个基于regex的调用

  • 我将字符串连接(
    +
    )替换为对
    -f
    的单个调用

  • 为了简洁起见,我用
    替换了
    Out文件

  • 我已将
    -Name
    添加到
    Get ChildItem
    调用中,以便输出与输入路径相关的路径字符串;如果需要绝对路径,请使用
    (获取ChildItem-LiteralPath$\递归)。全名>$outFile
    (或
    getchilditem-LiteralPath$|-Recurse | Select Object-ExpandProperty FullName>$outFile

至于你所尝试的:

您的问题是,您没有在
(…)
中包装通过字符串连接生成目标文件名的表达式,如果您想将表达式用作命令参数,这是必需的

请注意:

  • 在表达式中,字符串文字必须(完全)引用
  • $(…)
    仅在需要包装多个语句时才需要;否则,如果需要覆盖标准,请使用
    (…)
因此,您的原始命令可以通过以下方式修复:

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

很高兴听到这个消息,@matze;我的荣幸。