条件字符串与 powershell 连接?
Conditional string join with powershell?
我目前正在编写一段代码,该代码组合一个字符串以根据各种信息识别一个对象。其中一些信息可能并不总是可用,我想知道是否有聪明的方法可以使组装更容易?
例如,我们有构建最终标识符的片段 $a
、$b
和 $c
。其中 $b
可能为空,最终字符串应包含由 space 分隔的每个组件。一种选择是将 $b
的附加 space 添加到字符串本身,如下所示:
$a = "FirstPart"
$b = " SecondPart"
$c = "FinalPart"
Write-Output "$a$b $c"
#FirstPart SecondPart FinalPart
$b = ""
Write-Output "$a$b $c"
#FirstPart FinalPart
另一种选择是有条件(可能会变得相当复杂和冗长):
$a = "FirstPart"
$b = "SecondPart"
$c = "FinalPart"
if($b -eq ""){
Write-Output "$a $c"
}else{
Write-Output "$a $b $c"
#FirstPart SecondPart FinalPart
}
$b = ""
if($b -eq ""){
Write-Output "$a $c"
#FirstPart FinalPart
}else{
Write-Output "$a $b $c"
}
实际上非常需要的是使用 -join
或者 -f
来获得条件 space 如果 $b
不为空。有什么办法可以做到这一点或其他选择吗? ($a,$b,$c) -join ' '
如果 $b
为空,则结果为双 space。
$a = "FirstPart"
$b = "SecondPart"
$c = ""
$e = "last"
#put in array, and filter empty
$arr = ($a, $b, $c, $e) | ? { $_ }
#print in space separed
Write-Output "$arr"
我目前正在编写一段代码,该代码组合一个字符串以根据各种信息识别一个对象。其中一些信息可能并不总是可用,我想知道是否有聪明的方法可以使组装更容易?
例如,我们有构建最终标识符的片段 $a
、$b
和 $c
。其中 $b
可能为空,最终字符串应包含由 space 分隔的每个组件。一种选择是将 $b
的附加 space 添加到字符串本身,如下所示:
$a = "FirstPart"
$b = " SecondPart"
$c = "FinalPart"
Write-Output "$a$b $c"
#FirstPart SecondPart FinalPart
$b = ""
Write-Output "$a$b $c"
#FirstPart FinalPart
另一种选择是有条件(可能会变得相当复杂和冗长):
$a = "FirstPart"
$b = "SecondPart"
$c = "FinalPart"
if($b -eq ""){
Write-Output "$a $c"
}else{
Write-Output "$a $b $c"
#FirstPart SecondPart FinalPart
}
$b = ""
if($b -eq ""){
Write-Output "$a $c"
#FirstPart FinalPart
}else{
Write-Output "$a $b $c"
}
实际上非常需要的是使用 -join
或者 -f
来获得条件 space 如果 $b
不为空。有什么办法可以做到这一点或其他选择吗? ($a,$b,$c) -join ' '
如果 $b
为空,则结果为双 space。
$a = "FirstPart"
$b = "SecondPart"
$c = ""
$e = "last"
#put in array, and filter empty
$arr = ($a, $b, $c, $e) | ? { $_ }
#print in space separed
Write-Output "$arr"