Search code examples
powershellwindows-10powershell-5.0

Getting a multi-dimensional array from a text file in powershell


So, this should be a simple one but I am scratching my head with it. I have an array that I need passed in this format

$itemArray = @(('Valley1','111.111.111'), ('Valley2','111.111.112'), ('Valley3','111.111.113'));

And I need to get it from a text file that is formatted like this

Valley1,111.111.111
Valley2,111.111.112
Valley3,111.111.113

My code is currently throwing an error of "Cannot convert argument "items" with value "System.Object[]" So I am trying to figure out the best way to get from point A, the text file, to point B, the $itemArray format I need with that data, attached is the code below, thanks for looking!

https://pastebin.com/nyMtcczF


Solution

  • Using the text file.

    Valley1,111.111.111
    Valley2,111.111.112
    Valley3,111.111.113
    

    This should work.

    $Arrays = @()
    Get-Content C:\TEST\Test.txt | ForEach-Object{
        $Arrays += , @($_ -split ",")
    }
    
    $Arrays[0]
    

    This would return...

    Valley1
    111.111.111