如何在管道中处理 $null [英] How to handle $null in the pipeline

查看:25
本文介绍了如何在管道中处理 $null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 PowerShell 代码中经常出现以下情况:我有一个返回对象集合的函数或属性,或者 $null.如果将结果推送到管道中,如果 $null 是唯一的元素,则您还处理管道中的元素.

I often have the following situation in my PowerShell code: I have a function or property that returns a collection of objects, or $null. If you push the results into the pipeline, you also handle an element in the pipeline if $null is the only element.

示例:

$Project.Features | Foreach-Object { Write-Host "Feature name: $($_.Name)" }

如果没有功能($Project.Features 返回 $null),您将看到一行带有功能名称:".

If there are no features ($Project.Features returns $null), you will see a single line with "Feature name:".

我看到了三种解决方法:

I see three ways to solve this:

if ($Project.Features -ne $null)
{
  $Project.Features | Foreach-Object { Write-Host "Feature name: $($_.Name)" }
}

$Project.Features | Where-Object {$_ -ne $null) | Foreach-Object { 
  Write-Host "Feature name: $($_.Name)" 
}

$Project.Features | Foreach-Object { 
  if ($_ -ne $null) {
    Write-Host "Feature name: $($_.Name)" }
  }
}

但实际上我不喜欢这些方法中的任何一种,但是您认为最好的方法是什么?

But actually I don't like any of these approaches, but what do you see as the best approach?

推荐答案

我认为任何人都不喜欢foreach ($a in $null) {}"和$null | foreach-object{}" 迭代一次.不幸的是,除了您所演示的方法之外,没有其他方法可以做到这一点.你可以更简洁:

I don't think anyone likes the fact that both "foreach ($a in $null) {}" and "$null | foreach-object{}" iterate once. Unfortunately there is no other way to do it than the ways you have demonstrated. You could be pithier:

$null | ?{$_} | % { ... }

?{$_}where-object {$_ -ne $null} 作为 $null 的简写布尔表达式将被视为 $false

the ?{$_} is shorthand for where-object {$_ -ne $null} as $null evaluated as a boolean expression will be treated as $false

我在我的个人资料中定义了一个过滤器,如下所示:

I have a filter defined in my profile like this:

filter Skip-Null { $_|?{ $_ } }

用法:

$null | skip-null | foreach { ... }

过滤器与函数相同,只是默认块是 process {} 而不是 end {}.

A filter is the same as a function except the default block is process {} not end {}.

UPDATE:从 PowerShell 3.0 开始,$null 不再作为集合可迭代.耶!

UPDATE: As of PowerShell 3.0, $null is no longer iterable as a collection. Yay!

-Oisin

这篇关于如何在管道中处理 $null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆