Powershell trying and failing to cast a PSObject to Int32

回眸只為那壹抹淺笑 提交于 2021-02-08 10:49:41

问题


$tabName = "EventsTable"
#Create Table object
$table = New-Object system.Data.DataTable "$tabName"

#Define Columns
$col1 = New-Object system.Data.DataColumn EventID,([Int32])

$col2 = New-Object system.Data.DataColumn EventDate,([datetime])
$col3 = New-Object system.Data.DataColumn Instances,([Int32])

#Add the columns
$table.Columns.add($col1)
$table.Columns.add($col2)
$table.Columns.add($col3)

#Enter data in the row
$systemEvents = get-eventlog `
    -newest 1000 `
    -LogName System `
    -EntryType Information `
    -After (Get-Date).AddDays(-3);

for ($i=0; $i -lt 1; $i++) { #$systemEvents.Count
    #Create a row
    $row = $table.NewRow()
    $row.EventID = $systemEvents.Get($i).EventID
}

The penultimate line of code fails due to an "Exception setting

 "EventID": 
 "Unable to cast object of type 'System.Management.Automation.PSObject' to 
 type 'System.IConvertible'.Couldn't store <2010> in EventID Column.  
 Expected type is Int32."

However if I change this line to...

$systemEvents.Get($i).EventID.GetType()

The output is Int32.

If EventID is a PSObject how do I get the Int32 out of it? If EventID is an Int32 then what is PowerShell complaining about?

Thanks for your time


回答1:


As iRon said:

Just add [int] or [int32]in front:

$row.EventID = [int]$systemEvents.Get($i).EventID


来源:https://stackoverflow.com/questions/47727369/powershell-trying-and-failing-to-cast-a-psobject-to-int32

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!