Powershell v2 和 PowerShell v3 对象处理
Powershell v2 and PowerShell v3 Object handling
当我在 powershell v2 中创建对象时,我无法访问 powershell 成员属性,这将与 PowerShell V3 一起流畅地工作。例如如果我在 v3 中创建以下对象,
$Services = @();
$item = @{};
$item.Name = "ServiceName";
$item.Action = 2;
$item.ActionTime = Get-Date -Format "yyyy-MM-dd HH:mm:ss";
$obj = New-Object PSObject -Property $item;
$Services = $Services + $obj
我可以访问 $services.Action,这将是 2,无论在 PowerShell v2 上它是否为空。
有什么帮助吗?
谢谢
根据您是要列出所有操作还是仅列出特定索引,您可以使用:
$Services | Select -ExpandProperty Action
或(在第一个服务的情况下):
$Services[0].Action
这实际上是因为您将对象包装在数组中。
在 v2 中,要获取对象数组的所有 Action
属性,您可以这样做:
$Services | ForEach-Object { $_.Action }
# or
$Services | Select-Object -ExpandProperty Action
在 PowerShell v3 中,不再需要:
$Services.Action
会自动执行相同的操作。
此外,如果您刚刚完成 $obj.Action
它也会在 v2 中工作(仅针对那个对象)。
当我在 powershell v2 中创建对象时,我无法访问 powershell 成员属性,这将与 PowerShell V3 一起流畅地工作。例如如果我在 v3 中创建以下对象,
$Services = @();
$item = @{};
$item.Name = "ServiceName";
$item.Action = 2;
$item.ActionTime = Get-Date -Format "yyyy-MM-dd HH:mm:ss";
$obj = New-Object PSObject -Property $item;
$Services = $Services + $obj
我可以访问 $services.Action,这将是 2,无论在 PowerShell v2 上它是否为空。
有什么帮助吗?
谢谢
根据您是要列出所有操作还是仅列出特定索引,您可以使用:
$Services | Select -ExpandProperty Action
或(在第一个服务的情况下):
$Services[0].Action
这实际上是因为您将对象包装在数组中。
在 v2 中,要获取对象数组的所有 Action
属性,您可以这样做:
$Services | ForEach-Object { $_.Action }
# or
$Services | Select-Object -ExpandProperty Action
在 PowerShell v3 中,不再需要:
$Services.Action
会自动执行相同的操作。
此外,如果您刚刚完成 $obj.Action
它也会在 v2 中工作(仅针对那个对象)。