Powershell尝试并且未能将PSObject强制转换为Int32

时间:2017-12-09 09:56:48

标签: powershell

$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
}

倒数第二行代码由于“异常设置

而失败
 "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."

但是,如果我将此行更改为...

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

输出为Int32。

如果EventID是PSObject,我如何从中获取Int32?如果EventID是Int32,那么PowerShell会抱怨什么?

感谢您的时间

1 个答案:

答案 0 :(得分:0)

正如iRon所说:

只需在前面添加[int]或[int32]:

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