如何格式化多行字符串?

时间:2019-10-22 10:36:41

标签: powershell powershell-4.0

我正在尝试在Powershell中格式化多行字符串。

$json =
@'
{
    "updateDetails": [{
            "datasourceSelector": {
                "datasourceType": "AnalysisServices",
                "connectionDetails": {
                    "server": "{0}"
                }
            }
        }
    ]
}
'@
$json = [string]::Format($json, $name)

最后一行给出了错误

  

使用“ 2”个参数调用“格式”的异常:“输入字符串的格式不正确。”

我也尝试使用符号'@ -f $name,但遇到此错误。

  

格式化字符串时出错:输入字符串的格式不正确

我也尝试过这样转义字符串中的引号,但会遇到相同的错误

`"{0}`"

如何格式化多行字符串?

2 个答案:

答案 0 :(得分:3)

C# Tips and Tricks #7 – Escaping ‘{‘ in C# String.Format

$json =
@'
{{
    "updateDetails": [{{
            "datasourceSelector": {{
                "datasourceType": "AnalysisServices",
                "connectionDetails": {{
                    "server": "{0}"
                }}
            }}
        }}
    ]
}}
'@
[string]::Format($json, $name)

答案 1 :(得分:2)

一种方法是使用-replace代替格式:

$name = 'MyServer'
$json = @'
{
    "updateDetails": [{
            "datasourceSelector": {
                "datasourceType": "AnalysisServices",
                "connectionDetails": {
                    "server": "{0}"
                }
            }
        }
    ]
}
'@
$json -replace '\{0}', $name  # the opening curly bracket needs to be escaped

或在here字符串上使用双引号并将变量$name直接放入其中:

$name = 'MyServer'
$json = @"
{
    "updateDetails": [{
            "datasourceSelector": {
                "datasourceType": "AnalysisServices",
                "connectionDetails": {
                    "server": "$name"
                }
            }
        }
    ]
}
"@