使用powershell进行条件字符串连接?

Set*_*eth 0 string powershell concat concatenation

我目前正在编写一段代码,该代码组合一个字符串以根据各种信息识别一个对象。其中一些信息可能并不总是可用,我想知道是否有聪明的方法使组装更容易?

作为一个例子,我们有件$a$b$c认为建立最终的标识符。其中$b可能是空的,最终的字符串应包含由空格分隔的每个组件。一种选择是为$b字符串本身添加额外的空间,如下所示:

$a = "FirstPart"
$b = " SecondPart"
$c = "FinalPart"
Write-Output "$a$b $c"
#FirstPart SecondPart FinalPart
$b = ""
Write-Output "$a$b $c"
#FirstPart FinalPart
Run Code Online (Sandbox Code Playgroud)

另一种选择是有一个条件(可能会变得相当复杂和冗长):

$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"
}
Run Code Online (Sandbox Code Playgroud)

实际上非常需要的是使用-join或可能-f获得条件空间(如果$b不为空)。有什么办法可以做到这一点,或者有其他选择吗?($a,$b,$c) -join ' '如果$b为空,则结果为双倍空格。

dov*_*vid 5

$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"
Run Code Online (Sandbox Code Playgroud)