构建 PSCustomObject 时的 PowerShell 条件语句

标签 powershell pscustomobject

我想在创建 PSCustomObject 时检查变量是否存在。我有相当多的对象需要查询并将数据收集到我的新对象中,因此我不想用“if”语句复制整个代码块,因为我试图简洁。

[array]$newObject += [PSCustomObject][ordered]@{
  JitterInterArrival = (if ($_.QoeReport.AudioStreams){$_.QoeReport.AudioStreams[0].JitterInterArrival}else{"N/A"}
}

我知道上面的 block 会产生一个错误,即“if”语句无法识别。是否有另一种方法可以在定义 PSCustomObject 时包含代码块?

最佳答案

你们非常接近!

[array]$newObject += [PSCustomObject][ordered]@{
  JitterInterArrival = $(if ($_.QoeReport.AudioStreams){$_.QoeReport.AudioStreams[0].JitterInterArrival}else{"N/A"})
}

通过用 $() 包围它,我们使其成为首先执行的子表达式。

关于构建 PSCustomObject 时的 PowerShell 条件语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44805393/

相关文章:

powershell - 限制 Get-ChildItem 递归深度

powershell - 更改对象中列的顺序

powershell - 如何将 System.Collections.ArrayList 添加到 PowerShell 自定义对象?

PowerShell:将 16MB CSV 导入 PowerShell 变量会创建 >600MB 的 PowerShell 内存使用量

powershell - 通过符号名称(键)访问脚本的多个输出

powershell - 在 Powershell for 循环的 <init> 部分使用多个命令

parsing - 我正在尝试使用Powershell解析非标准的RSS提要

powershell - 如何使用 PSCustomObjects 对对象进行不可变的更改?

powershell - 将pscustomobject传递到Start-Job脚本 block 时,为什么脚本属性丢失?

html - 在页面上查找元素而不搜索整个文档