Trying to parse a text file using PowerShell and create a list of sections present in the file. While executing the below code snippet, error is thrown when the object is added to the list.
Method invocation failed because [System.Management.Automation.PSObject] does not contain a method named 'op_Addition'.
The first object gets added to the list but second object onward error is thrown. Interestingly, the error does not occur if the program runs in debug mode.
function Process-Master-File {
[CmdletBinding()]
Param (
[Parameter(ValueFromPipeline = $true)][String[]]$PipeValue
)
Begin {
#create new section object
$codeSection = New-Object -TypeName psobject
$codeSection | Add-Member -MemberType NoteProperty -Name Name -Value $null
$codeSection | Add-Member -MemberType NoteProperty -Name SuppresionGroup -Value $null
$codeSection | Add-Member -MemberType NoteProperty -Name Mandatory -Value $False
$codeSection | Add-Member -MemberType NoteProperty -Name SectionBody -Value $null
[string]$out = ""
}
Process {
# Grab a line from the pipe
[string]$line = $_
# Find positions
try {
$pos = 0
$pos = $line.IndexOf('@Section')
if ($pos[0] -ne -1) {
if ($objTemp.Name) {
$objTemp.SectionBody = $section
$codeSectionList += $objTemp # Error is thrown here
$section = ""
}
$objTemp = $codeSection | Select-Object *
$objTemp.Name = $line.Substring($line.LastIndexOf(':') + 1).TrimEnd().TrimStart()
$objTemp.SuppresionGroup = $line.Substring($line.IndexOf('@SG') + 3, ($line.LastIndexOf(':') - $line.IndexOf('@SG') - 3)).TrimEnd().TrimStart()
if ($line.IndexOf('@Mandatory') -ne -1) {
$objTemp.Mandatory = $True
}
$section = $line
Write-Verbose $line
}
else {
$section += $line
}
}
Catch {
Write-Host "An error occurred while processing file:"
Write-Host $_
}
}
End {
$codeSectionList
}
}