$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
}
I've replaced the multiple .Replace()
method calls with a single, regex-based call to PowerShell's -replace
operator.
I've replaced string concatenation (+
) with a single call to PowerShell's format operator, -f
.
I've replaced Out-File
with >
for brevity.
- I've added
-Name
to the Get-ChildItem
call so that path strings relative to the input path are being output; if you want absolute paths, use
(Get-ChildItem -LiteralPath $_ -Recurse).FullName > $outFile
instead (or
Get-ChildItem -LiteralPath $_ -Recurse | Select-Object -ExpandProperty FullName > $outFile
).
As for what you tried:
Your problem was that you didn't wrap the expression that built the target filename via string concatenation in (...)
, which is necessary if you want to use an expression as a command argument.
Note that:
- inside an expression, string literals must be (fully) quoted
$(...)
is only needed if you need to wrap multiple statements; otherwise, if needed to override standard operator precedence, use (...)
.
Thus, your original command could be fixed with:
... | Out-File ('C:\Test\Output\computername_' + $_.replace("\","_").replace(":","") + '.txt')