OwlsSleeping
OwlsSleeping

Reputation: 1570

Powershell Select-Object calculated property data type

I've added a calculated column using Select-Object.

$ParsedContent = $ContentSplit.Groups[2].Value |  
    ConvertFrom-String -TemplateFile $TemplatePath |
        Select-Object -Property *,
            @{Name = 'ParcelNo' ; Expression = {[int]::parse($_.Reference.SubString(0,3))}}

When I then attempt to use this ParcelNo value in another function, it gives me an error that the value is PSObject rather than Int32.

Write-SqlTableData @SqlArguments
     |      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Unable to cast object of type 'System.Management.Automation.PSObject' to type 'System.IConvertible'.Couldn't store <1> in ParcelNo Column. 
     | Expected type is Int32.

Checking type using GetType() shows Int32, but inspecting variables in VSCode shows PSObject instead.

Any idea why these would be different? How would I make sure that the calculated property is an actual Int32.

Int32 Image PSObject

Powershell version 7.0.3

Edit: Here's how building SqlArguments looks. Sorry it's a bit convoluted, I might refactor some bits of that eventually. The ParseTxt function is the bit containing $ParsedContent from my screenshot.

$DataToUpload = @()
Foreach($File in $FilesToProcess){
    $DataToUpload += (ParseTxt -Path $File.FullName -TemplatePath $TemplatePath)
}

$SqlArguments = @{
    InputData = $DataToUpload
    ServerInstance = 'myserver'
    DatabaseName = 'mydb'
    SchemaName = 'dbo'
    TableName = 'mytable'
}

Upvotes: 1

Views: 626

Answers (1)

OwlsSleeping
OwlsSleeping

Reputation: 1570

For future readers, here's the workaround I used-

Foreach($DataRow in $DataToUpload){
    $DataRow.ParcelNo = [int]$DataRow.ParcelNo
}

If somebody comes up with a proper solution that handles it during the initial Select-Object rather than requiring a workaround afterwards, I'll accept that as answer.

Upvotes: 1

Related Questions