首页 > 解决方案 > Powershell - 在 Here-String 内替换

问题描述

我需要在if里面使用语句here-string。但是当我查看变量内部时,我看到true而不是$true 表达式$($row.'Secondary Network Adapter' -eq 'Y')将被替换为$trueor $false

$row = @{
    SecondaryNetworkAdapter = "Y"
}

$code1 = @'
    if($($row.SecondaryNetworkAdapter -eq 'Y')){
        Set-NetIPInterface -InterfaceAlias '$nic1Name' -AutomaticMetric disabled -InterfaceMetric 5
    }
'@

然后,我正在运行以下行:

$ExecutionContext.InvokeCommand.ExpandString($code1)

输出:

if(True){
  Set-NetIPInterface -InterfaceAlias 'LAN' -AutomaticMetric disabled -InterfaceMetric 5
}

亲切的问候,

标签: powershell

解决方案


$在表达式前添加转义文字:

if(`$$($row.SecondaryNetworkAdapter -eq 'Y')){

推荐阅读