How to feed a table with results from foreach

Welcome Forums General PowerShell Q&A How to feed a table with results from foreach

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

 
Participant
1 year ago.

  • Author
    Posts
  • #89146

    Participant
    Points: 0
    Rank: Member

    I am copying files to multiple locations and then do a check against the source to see if each file exists in each location.

    I want to have the result in a table like below, but can't figure out how to do it.

    FileName Dstn1 Dstn2 Dstn3
    ——– —– —– —–
    A.xml yes yes yes
    B.xml yes yes yes
    C.xml yes yes yes

    Here is my code

    $Prod_SRCDIR1 = "C:\temp\Copy\00_S"
    $Prod_DST = "C:\temp\Copy\01_D","C:\temp\Copy\02_D","C:\temp\Copy\03_D"
    $Prod_DST1 = "C:\temp\Copy\01_D"
    $Prod_DST2 = "C:\temp\Copy\02_D"
    $Prod_DST3 = "C:\temp\Copy\03_D"

    $Prod_DST | %{Copy-Item $Prod_SRCDIR1\*.xml -Destination $_ -Force}
    $FileList = Get-ChildItem -Path $Prod_SRCDIR1\*.xml | Select -ExpandProperty Name
    Foreach ($item in $FileList){
    $Prod_DST |
    % {if (Test-Path ($_ + "\" + "$item")){
    write-host $item exist in $_ -ForegroundColor Green
    }else{
    write-host $item does not exist in $_ -ForegroundColor Red
    }
    }
    }

  • #89147

    Participant
    Points: 91
    Rank: Member
    # Input
    $SourceFolder = "C:\temp\Copy\00_S"
    $DestinationFolders = "C:\temp\Copy\01_D","C:\temp\Copy\02_D","C:\temp\Copy\03_D"
    
    # Copy
    $DestinationFolders | % { Copy-Item -Path $SourceFolder\*.xml -Destination $_ -Force }
    
    # Validation
    $FileList = Get-ChildItem -Path $SourceFolder\*.xml | Select -ExpandProperty Name
    $myOutput = Foreach ($item in $FileList){
        $Props = [Ordered]@{ FileName = $item }
        $DestinationFolders | % {
            if (Test-Path ($_ + "\" + "$item")){
                write-host $item exist in $_ -ForegroundColor Green
                $Props.Add($(Split-Path $_ -Leaf),'yes')
            } else {
                write-host $item does not exist in $_ -ForegroundColor Red
                $Props.Add($(Split-Path $_ -Leaf),'no')
            }
        }
        New-Object -TypeName PSObject -Property $Props
    }
    $myOutput
    

    You can also simply validate success/failure of the copy-item cmdlet by enclosing it in a try/catch block, and build up your $myOutput object based on that..

    • #89153

      Participant
      Points: 0
      Rank: Member

      Wow !!! it works so well. Thank you so much. Took me 2 days could not figure it out....

The topic ‘How to feed a table with results from foreach’ is closed to new replies.