piping with copy-item

Hello all.

I’m a couple days into this, so total noob. I’m trying to get a directory name via input from user and then name the folder with that variable and copy data to it.

$directory= Read-Host 'Enter Userid' | copy-item "C:\ProgramData\microsoft\windows\start menu\programs" -destination "c:\labs\backup\$directory\programs" -recurse

I can get both sides of the pipe to work alone, minus the variable in the 2nd part of course. Any one free to point out the reason this fails? and possibly offer and alternative?

Thank you,


Read-Host 'Enter Userid' | 
foreach-object { 
copy-item 'C:\ProgramData\microsoft\windows\start menu\programs' -destination "c:\labs\backup\$_\programs" -recurse }

Thanks for the help, that worked perfectly. I will go do some reading about “foreach”.

Thanks again.

You’re welcome. That’s actually ‘foreach-object’. Forgive my aliasing. There’s also a ‘foreach($item in $group)’ statement that’s different, and may cause you some confusion.

I was hoping I could just make a variable and use it over and over to help reference a directory for lots of different data copying. I’m just fooling around trying to write a little backup program that takes a bunch of various folders and dumps them into 1 folder. In my original attempt, was I using the variable wrong? I was under them impression I could just type the variable and it assumes the variable’s value.

Why pipe at all then?

$directory = Read-Host 'Enter Userid'
copy-item 'C:\ProgramData\microsoft\windows\start menu\programs' -destination "c:\labs\backup\$directory\programs" -recurse

lol, I should probably keep reading my book some more. I don’t know when to pipe and when not to.

I just added a slew of “copy-item” commands beneath it. Worked perfect. I was soooo close :). Just 1 little ‘|’ messed it all up.

Again, thanks for the conversation and help. Very appreciated.:slight_smile: