如何格式化多行字符串?
How to format a multiline string?
我正在尝试在 powershell 中格式化多行字符串。
$json =
@'
{
"updateDetails": [{
"datasourceSelector": {
"datasourceType": "AnalysisServices",
"connectionDetails": {
"server": "{0}"
}
}
}
]
}
'@
$json = [string]::Format($json, $name)
最后一行报错
Exception calling "Format" with "2" argument(s): "Input string was not in a correct format."
我也试过符号 '@ -f $name
但出现此错误。
Error formatting a string: Input string was not in a correct format
我也试过像这样转义字符串中的引号,但得到同样的错误
`"{0}`"
如何设置多行字符串的格式?
C# Tips and Tricks #7 – Escaping ‘{‘ in C# String.Format
$json =
@'
{{
"updateDetails": [{{
"datasourceSelector": {{
"datasourceType": "AnalysisServices",
"connectionDetails": {{
"server": "{0}"
}}
}}
}}
]
}}
'@
[string]::Format($json, $name)
一种方法是使用 -replace
而不是格式:
$name = 'MyServer'
$json = @'
{
"updateDetails": [{
"datasourceSelector": {
"datasourceType": "AnalysisServices",
"connectionDetails": {
"server": "{0}"
}
}
}
]
}
'@
$json -replace '\{0}', $name # the opening curly bracket needs to be escaped
或者在此处的字符串上使用双引号并直接将变量$name
放入其中:
$name = 'MyServer'
$json = @"
{
"updateDetails": [{
"datasourceSelector": {
"datasourceType": "AnalysisServices",
"connectionDetails": {
"server": "$name"
}
}
}
]
}
"@
我正在尝试在 powershell 中格式化多行字符串。
$json =
@'
{
"updateDetails": [{
"datasourceSelector": {
"datasourceType": "AnalysisServices",
"connectionDetails": {
"server": "{0}"
}
}
}
]
}
'@
$json = [string]::Format($json, $name)
最后一行报错
Exception calling "Format" with "2" argument(s): "Input string was not in a correct format."
我也试过符号 '@ -f $name
但出现此错误。
Error formatting a string: Input string was not in a correct format
我也试过像这样转义字符串中的引号,但得到同样的错误
`"{0}`"
如何设置多行字符串的格式?
C# Tips and Tricks #7 – Escaping ‘{‘ in C# String.Format
$json =
@'
{{
"updateDetails": [{{
"datasourceSelector": {{
"datasourceType": "AnalysisServices",
"connectionDetails": {{
"server": "{0}"
}}
}}
}}
]
}}
'@
[string]::Format($json, $name)
一种方法是使用 -replace
而不是格式:
$name = 'MyServer'
$json = @'
{
"updateDetails": [{
"datasourceSelector": {
"datasourceType": "AnalysisServices",
"connectionDetails": {
"server": "{0}"
}
}
}
]
}
'@
$json -replace '\{0}', $name # the opening curly bracket needs to be escaped
或者在此处的字符串上使用双引号并直接将变量$name
放入其中:
$name = 'MyServer'
$json = @"
{
"updateDetails": [{
"datasourceSelector": {
"datasourceType": "AnalysisServices",
"connectionDetails": {
"server": "$name"
}
}
}
]
}
"@