Convert txt to a object

Viewed 62

I would like to convert the content of this file (the first two columns, BARCODE and LOCATION) to object, but I am stuck creating the object..



#BARCODE     LOCATION    LIBRARY            STATUS    COPY
#-------     --------    -------            ------    ----
#L40001L8    slot 41     DRP_TAPE_DRPLTO    Full      Primary_Global
#L40002L8    slot 96     DRP_TAPE_DRPLTO    Full      Primary_Global
#L40034L8    IEPort2     DRP_TAPE_DRPLTO    Full      Primary_Global

$object= @{}
ForEach ($i in $(gc "C:\temp\tapes.txt"))
 { 

 $object.BARCODE= ($i.ToString().Substring(0,8))
 $object.LOCATION= ($i.ToString().Substring(0,19))
 New-Object psobject -Property $object
 } 

Can anyone help me?

2 Answers

Use creating object from hashtable:

$ht = @{ 'key1' = 'value1'; key2 = 'value2' }
$ht['key3'] = 'value3'
$o = [PSCustomObject]$ht

When you have fixed-width columns:

$lines = @(@'
#BARCODE     LOCATION    LIBRARY            STATUS    COPY
#-------     --------    -------            ------    ----
#L40001L8    slot 41     DRP_TAPE_DRPLTO    Full      Primary_Global
#L40002L8    slot 96     DRP_TAPE_DRPLTO    Full      Primary_Global
#L40034L8    IEPort2     DRP_TAPE_DRPLTO    Full      Primary_Global
'@ -split "`r`n" )

# $lines = [System.IO.File]::ReadAllLines($filePath)

$lines = $lines | Select-Object -Skip 2
$objects = $lines | % {
    return [PSCustomObject]@{
        BARCODE  = $_.Substring(1,8).Trim()
        LOCATION = $_.Substring(13,8).Trim()
    }
}

$objects

First of all, The content of the file looks very much like you have started off with an array of objects, then 'stringyfied' that using Format-Table and copy/pasted the output from the console to your textfile. Why every line is now commented by placing # in front, I don't know. Perhaps you did this to format the question in SO?

What I'm trying to say is that if that is indeed what happened, then it would make much more sense to change the script you used to create the file by removing the Format-Table from the code and saving the object array using a cmdlet like Export-Csv, or by saving as JSON or XML..

Anyway, if you have no choice in the matter and need to convert that file back to objects, you can do this:

# read the file line-by-line and replace the whitespaces with a comma
$data = switch -Regex -File 'D:\Test\File1.txt' {
    '^#[^-]'  { $_.TrimStart("#") -replace '\s+', ',' }

    # if the comment marks '#' are NOT in the file, use this instead
    # '^[^-]'  { $_ -replace '\s+', ',' }
}

$result = $data | ConvertFrom-Csv | Select-Object BARCODE, LOCATION

# output on screen
$result

# output to CSV file
$result | Export-Csv -Path 'D:\Test\Output1.csv' -UseCulture -NoTypeInformation

Output on screen will look like

BARCODE  LOCATION
-------  --------
L40001L8 slot    
L40002L8 slot    
L40034L8 IEPort2 

You can simply double-click the Output1.csv file to open in Excel

Related