如何条件中弦

How do condition mid-string

我的 psobject 中有一个字符串,它只适用于 10 个设备,而不适用于第 11 个设备。如果是第 11 个变量,如何构造一个字符串而不包含一个变量?

这对我的 foreach 中的前 10 个有效:

$INFO_Tab = New-Object psobject -Property $([ordered]@{
                DEVICE = "$($currentDevice)"
                Platform = "Name"
                Device_Error_Description = "ErrorCodeList files \Retail\Tools\ServiceEndToEnd\ErrorCodeList "
                OCP_Display = "sdkDesc in $BaseName $($cppFile)" #$BaseName doesn't apply for $currentDevice="Scanner"
                ...
})
$xlsx = $INFO_Tab | Export-Excel -Path $outFilePathExcel -WorksheetName "Source" -Autosize -AutoFilter -FreezeTopRow -BoldTopRow  -PassThru

我可以为 OCP_Display 行做这样的事情吗?我找不到例子。

OCP_Display = "sdkDesc in"+ if($currentDevice="Scanner"):"":$BaseName +$($cppFile)"

这是 PowerShell 5.1 和 VSCode。

if 语句包装在子表达式中 $():

"sdkDesc in $(if($currentDevice -ne 'Scanner'){"$BaseName "})$($cppFile)"

看起来你需要 $() 而不仅仅是 () 甚至在字符串之外。除此之外,它有助于了解 powershell 基础知识。

$currentdevice = 'Unscanner'
$basename = 'Basename'
$cppfile = 'Cppfile'
"Prefix" + $(if($currentDevice -eq "Scanner"){""}else{$BaseName}) + $cppFile

PrefixBasenameCppfile


$currentdevice = 'scanner'
"Prefix" + $(if($currentDevice -eq "Scanner"){""}else{$BaseName}) + $cppFile

PrefixCppfile