ForEach Issue

Welcome Forums General PowerShell Q&A ForEach Issue

This topic contains 2 replies, has 2 voices, and was last updated by

3 years, 11 months ago.

  • Author
  • #23567

    Points: 0
    Rank: Member

    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.


  • #23571

    Points: 166
    Helping Hand
    Rank: Participant


    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

    Points: 0
    Rank: Member

    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.

The topic ‘ForEach Issue’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort