In my script I am attempting to create PowerShell objects from a text file. Here is a sample of a text file.
junk data at the
beginning of
the file
Item: Car
In Stock: YES
Make: Ford
Model: Taurus
Color: Blue
Miles: 0
Item: Car
Miles: 0
Item: Truck
Item: SUV
Item: Car
In Stock: YES
Make: Honda
Model: Civic
Color: Red
Miles: 0
junk
data at the
end
Sometimes these files are generated with junk data at the beginning and end. I try to account for this with my Select-String statement.
Here is my script:
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[string]$File
)
class Item {
[string] $Item = ''
[string] $Found = 'NO'
[string] ${In Stock} = 'N/A'
[string] $Make = 'N/A'
[string] $Model = 'N/A'
[string] $Color = 'N/A'
[string] $Miles = 'N/A'
}
[string[]]$Keep = @("Item:", "In Stock:", "Make:", "Model:", "Color:", "Miles:")
(Get-Content $File | Select-String -Pattern ($Keep -join "|") |
Out-String) -split '(?m)(?=^Item:)' -ne '' -replace '(?m)^(.+?):', '$1=' |
ConvertFrom-StringData | ForEach-Object {
$Obj = [Item] $_
if ($Obj.'In Stock' -eq 'Yes') {
$Obj.Found = 'YES'
}
Write-Output $Obj
}
The script works a lot better than it did. Many thanks to another user that helped me get this far.
When I run the script, I get an EXTRA object at the top with all the default values defined in the class. Why is that?
Here is the output:
Item:
Found: NO
In Stock: N/A
Make: N/A
Model: N/A
Color: N/A
Miles: N/A
Item: Car
Found: YES
In Stock: YES
Make: Ford
Model: Taurus
Color: Blue
Miles: 0
Item: Car
Found: NO
In Stock: N/A
Make: N/A
Model: N/A
Color: N/A
Miles: 0
Item: Truck
Found: NO
In Stock: N/A
Make: N/A
Model: N/A
Color: N/A
Miles: N/A
Item: SUV
Found: NO
In Stock: N/A
Make: N/A
Model: N/A
Color: N/A
Miles: N/A
Item: Car
Found: YES
In Stock: YES
Make: Honda
Model: Civic
Color: Red
Miles: 0