ForEach Issue

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Tee Tee 1 year, 8 months ago.

  • Author
    Posts
  • #23567
    Profile photo of Tee
    Tee
    Participant

    Hello all, I'm new to powershell and I was wondering if someone can tell me what I'm doing wrong in the below code. Basically, all I'm trying to do is copy files from one directory to another and at the same time write-out to the ps console how many items were moved. Here is my script from the console

    PS C:\> $counter = 0
    PS C:\> copy-item -Path .\testFolder\*.* -Destination .\ testFolder2 | foreach-object -Process { $counter += 1 } | write-host "Item " + $counter + " has been moved."
    

    The copy process seems to be working but my $counter variable isn't incrementing and I'm not getting the output to my console.

    Thanks

  • #23571
    Profile photo of Sam Boutros
    Sam Boutros
    Participant

    try

    copy-item -Path .\testFolder\*.* -Destination .\testFolder2 -Verbose
    

    Simply use the -Verbose parameter to show files as they're being copied.

    In your code, the use of piping is not correct.

    Looking at the Copy-Item cmdlet:

    help Copy-Item -ShowWindow
    

    and looking under the OutPuts section, shows that it returns nothing unless the -PassThru parameter is used. For example:

    $counter = 0
    copy-item -Path .\testFolder\*.* -Destination .\testFolder2 -PassThru | 
        foreach-object -Process { 
            $counter ++ 
            Write-Output "Item $counter has been copied." 
        }
    

    I would use $counter ++ – personal preference
    I would use Write-Output not Write-Host (need I say why!?)
    No need for the '+' signs
    I would use 'copied' instead of 'moved' since it's more accurate representation of what was performed.

  • #23578
    Profile photo of Tee
    Tee
    Participant

    Thank you for the input. I knew about vebose but I was practicing at writing my own output. I'm fairly new at powershell and I'm still on the road of experimentation. Thanks greatly.

You must be logged in to reply to this topic.