在 PowerShell 中尝试将 PSObject 转换为 Int32 并失败 [英] Trying and failing to cast a PSObject to Int32 in PowerShell
本文介绍了在 PowerShell 中尝试将 PSObject 转换为 Int32 并失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑:
$tabName = "EventsTable";# 创建一个表对象$table = 新对象 system.Data.DataTable "$tabName";# 定义列$col1 = 新对象 system.Data.DataColumn EventID,([Int32])$col2 = 新对象 system.Data.DataColumn EventDate,([datetime])$col3 = 新对象 system.Data.DataColumn 实例,([Int32])# 添加列$table.Columns.add($col1)$table.Columns.add($col2)$table.Columns.add($col3)# 在行中输入数据$systemEvents = Get-EventLog `- 最新 1000 `-日志名称系统`-条目类型信息`-After (Get-Date).AddDays(-3);for ($i=0; $i -lt 1; $i++) { #$systemEvents.Count# 创建一行$row = $table.NewRow()$row.EventID = $systemEvents.Get($i).EventID}
倒数第二行代码由于异常设置"而失败
<块引用> EventID":"无法将类型为System.Management.Automation.PSObject"的对象转换为输入System.IConvertible".无法存储 <2010>在 EventID 列中.预期类型为 Int32."
但是,如果我将此行更改为...
$systemEvents.Get($i).EventID.GetType()
输出为 Int32.
如果 EventID 是 PSObject,我怎样才能把 Int32 弄出来呢?如果 EventID 是 Int32,那么 PowerShell 抱怨的是什么?
解决方案
As iRon 说,前面加[int]或[int32]:
$row.EventID = [int]$systemEvents.Get($i).EventID
Consider:
$tabName = "EventsTable"
# Create a 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?
解决方案
As iRon said, just add [int] or [int32] in front:
$row.EventID = [int]$systemEvents.Get($i).EventID
这篇关于在 PowerShell 中尝试将 PSObject 转换为 Int32 并失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文