views:

52

answers:

1

Hello! Today I started scripting in Windows PowerShell - so please excuse my "dumbness"...

I want to create txt-Files with the name of the subfolders of each "rootfolder" on drive G:. On G:\ I have the following folders:

1_data
2_IT_area
3_personal
4_apprenticeship
7_backup
8_archives
9_user_profile

So I wrote this script:

get-childitem G:\ | ForEach-Object -process {gci $_.fullName -R} | WHERE {$_.PSIsContainer} > T:\listing\fileListing+$_.Name+.txt

But the script isn't doing what I want - it's creating only one text file.. can u help me? I already tried it as described here >> http://www.powershellpro.com/powershell-tutorial-introduction/variables-arrays-hashes/ "T:\listing\$_.Name.txt" - doesn't work as well...

Thank u very much for your Help!

-Patrick

+1  A: 

This should do what you want:

Get-ChildItem G:\ | Where {$_.PSIsContainer} | 
    Foreach {$filename = "T:\fileListing_$($_.Name).txt"; 
             Get-ChildItem $_ -Recurse > $filename} 

And if typing this interactively (using aliases):

gci G:\ | ?{$_.PSIsContainer} | %{$fn = "T:\fileListing_$($_.Name).txt"; 
                                  gci $_ -r > $fn} 

The $_ special variable is typically only valid within a scriptblock { ... } either for a Foreach-Object, Where-Object, or any other pipeline related scriptblock. So the following filename construction T:\listing\fileListing+$_.Name+.txt isn't quite right. Typically you would expand a variable inside a string like so:

$name = "John"
"His name is $name"

However when you're accessing a member of an object like with $_.Name then you need to be able to execute an expression within the string. You can do that using the subexpression operator $() e.g.:

"T:\listing\fileListing_$($_.Name).txt"

All that filename string construction aside, you can't use $_ outside a scriptblock. So you just move the filename construction inside the Foreach scriptblock. Then create that file with the contents of the associated dir redirected to that filename - which will create the file.

Keith Hill
Thank you so much! - explained super precisely :) thanks a lot!