1

I would like to get the content from each path within pathlist.txt and each path content should be saved to his own pathname.txt file, named like the input path.

So something like this:


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

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

Input:

  • C:\Test\Test\Test
  • D:\Downloads
  • C:\Windows\Temp

Output:

  • computername_C_Test_Test_Test.txt
  • computername_D_Download.txt
  • computername_C_Windows_Temp.txt

Each output text file contains the result from Get-ChildItem -Recurse for the named path.

matze
  • 15
  • 6

2 Answers2

2
$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')
mklement0
  • 382,024
  • 64
  • 607
  • 775
0

it all seems to be ok but there are spelling issues. Try this:

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

And let me know.

WannabeDev
  • 35
  • 3