问题
$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