Powershell 如何将每个输出文件命名为Get Content中的每个输入行?
我想从pathlist.txt中的每个路径获取内容,每个路径内容都应该保存到自己的pathname.txt文件中,名称与输入路径类似 比如说: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 = 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
}
- 我已将多个
方法调用替换为对的单个基于regex的调用.Replace()
- 我将字符串连接(
)替换为对+
的单个调用-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;我的荣幸。