Read data from a text file line by line into a variable

# Read data from a plain text file line by line and put it into a variable

<#
let's say you have the file ReadData.txt in C:\Temp with the follwing contents:

[123]
{456}

[789]
{ABC}

#>



# 1. set the path for the .txt file we read data from
# Tip: you have to save your ps1 script for this command!!!

$myPath = $psISE.CurrentFile.FullPath

# e.g. $myPath would be "C:\Temp\ReadData.ps1" if you would save your script in C:\Temp with the name "ReadData.ps1"

# $BaseDir = up one level (= parent dir) -> e.g. C:\Temp
$BaseDir = ((Get-Item $myPath).Directory.FullName + "\")



# 2. create variables for the data read from the text file

$AllNames = [pscustomobject]@{
    OLD = [System.Collections.ArrayList]@()
    NEW = [System.Collections.ArrayList]@()
}



# 3. read the lines and process data

$importFile = Get-Content ($BaseDir + "ReadData.txt") -Encoding UTF8

foreach($importLine in $importFile)
{
    if($importLine -ne "")
    {
        if($importLine.StartsWith("["))
        {
            $temp = $importLine.Trim("[").Trim("]")
            [void]$AllNames.OLD.Add($temp)
        }

        if($importLine.StartsWith("{"))
        {
            $temp = $importLine.Trim("{").Trim("}")
            [void]$AllNames.NEW.Add($temp)
        }

    }
}
PowerShell

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *