Copy a file from each subdirectory to one folder

  • Hi,

    I'm trying to do something like this:

    Get-ChildItem -Path "\\drive\s*\*.txt" | ForEach-Object {

    Copy-Item "\\drive\Erik"

    }

    But it isn't working, and I'm not really getting anywhere with it. Any recommendations? I don't have a ton of time to research at the moment.

    Thanks

  • I finally figured something out:

    $files = ls "\\drive\S*" -recurse -Include *.txt |

    foreach-object {

    copy $_ "\\Drive\Erik"

    }

    The rest of what I was doing is this:

    Get-Content C:\path\*.txt | Out-File C:\path\whatever.txt -Encoding Unicode -Width 128

    $b = "blah blah file header"

    $a = (Get-Content C:\path\whatever.txt) |

    Foreach-Object {$_ -replace "some dumb crap", ""}|

    Foreach-Object {$_ -replace "other dumb crap", ""}|

    ##Foreach-Object {$_ -replace "yet more dumb crap", ""}|

    ? {$_.trim() -ne "" }

    Set-Content C:\path\whatevercleaned.txt -value $b, $a

    Essentially stripping out the file headers that were brought in with each text file along with some other junk characters, and then writing the cleaned data minus blank lines with one set of headers at the beginning of the file. I hope this helps someone out there.

  • Sorry Erik, I saw this on the mobile but you had figured it out by the time I have reached the desktop.

    For those who will read this post and cannot see the difference between Erik's problem and his solution, the solution adds $_ to the copy command (unless I am very much mistaken). $_ is the input to the current command which is the output from the previous command in the pipeline. In this case the output from ls in the solution and would have been the output of Get-ChildItem in the problem.

    For clarity ls is just an alias of Get-ChildItem.

    (Edited to correct heinous crime of misspelling of Erik's name!!!)

    Gaz

    -- Stop your grinnin' and drop your linen...they're everywhere!!!

  • Hi Gary,

    No problem. It just seemed like one of those tasks that PS is very suited to, and I thought there might be a neat trick to it. Thanks for explaining about the $_, I didn't know that. What I posted is every inch Frankencode. If you can see a way to do any of it better, I'm all for it.

    Thanks

  • Whilst the pipeline is quite useful I do find that single lines allow for output to the console whilst testing using Write-Host.

    Gaz

    -- Stop your grinnin' and drop your linen...they're everywhere!!!

  • :unsure:

  • erikd (11/15/2013)


    :unsure:

    It is easy to convert:

    $a = Some-CommandA

    Write-Host $a

    $b = Some-CommandB $a

    Write-Host $b

    $c = Some-CommandC $b

    Write-Host $c

    to:

    Some-CommandA | Some-CommandB $_ | Some-CommandC $_

    Gaz

    -- Stop your grinnin' and drop your linen...they're everywhere!!!

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply