<<< Back to Search

Objects - Initialize from CSV

Create/initialize a collection of objects from definition in a CSV (comma separated value) string.

Core Snippet and Sample

Copy text below into a power shell session and execute to see the code in action.

# Objects - Initialize from CSV
# Core Snippet &amp; Sample
# www.PowerShellExamples.com

# Initialize data on a CSV String -_-
$csvStr = @"
Source,Target
"Source A","Target 1"
"Source B","Target 2"
"Source C","Target 3"
"@

# Convert CSV String to Array of Objects -_-
$csvArr = ConvertFrom-Csv -InputObject $csvStr

# List every object converted from CSV lines -_-
Write-Host "Listing every object converted from CSV lines" -ForegroundColor DarkCyan
    $csvArr | foreach-object {
        $target = $_

        write-Host "Listing as object:"
        
        $target | Out-String | write-Host -ForegroundColor green
    }
    


Result

PS C:\>

Listing every object converted from CSV lines
Listing as object:

Source   Target  
------   ------  
Source A Target 1



Listing as object:

Source   Target  
------   ------  
Source B Target 2



Listing as object:

Source   Target  
------   ------  
Source C Target 3