string - 在包含花括号的字符串上使用 -f 运算符

请考虑以下此处的字符串,我正在尝试将模板用于我的 Nagios 定义。

$blankDefinition = @"
define host{
        use             windows-server  ; Inherit default values from a template
        host_name       {0}       ; The name we're giving to this host
        alias           {0}       ; A longer name associated with the host
        address         {1}     ; IP address of the host
        }

"@

我有一个脚本,它可以确定我的哪些服务器不应该在 nagois 中。当它循环时,我试图让它为我吐出一个定义,以便我可以复制并粘贴到我的 Nagios 配置中。

$comparison | %{
    $blankDefinition -f $($_.serverName),$($_.ipAddress)
}   

这让我犯了以下错误:

Error formatting a string: Input string was not in a correct format..

这样的东西很好用

@"
Testing
One
{0}
Three
"@ -f "Twelve"

然后我发现这是因为其他花括号。有没有一种方法可以在保留大括号的同时使用 -f 格式化我的字符串?还是我只能使用变量替换?

最佳答案

添加另一组花括号似乎有效:

$blankDefinition = @"
define host{{
        use             windows-server  ; Inherit default values from a template
        host_name       {0}       ; The name we're giving to this host
        alias           {0}       ; A longer name associated with the host
        address         {1}     ; IP address of the host
        }}

"@

$blankDefinition -f 'foo', 'bar', 'foo'

输出:

define host{
        use             windows-server  ; Inherit default values from a template
        host_name       foo       ; The name we're giving to this host
        alias           foo       ; A longer name associated with the host
        address         bar     ; IP address of the host
        }

https://stackoverflow.com/questions/25436058/

相关文章:

algorithm - 需要一种算法来拆分一系列数字

c# - 获取格式化字符串以表示 UTC 偏移量的最佳方法是什么?

javascript - json 值中的单引号

sql-server - SQL Server 2008 : how to format the o

c# - Linq 2 Sql DateTime 格式为字符串 yyyy-MM-dd

html - html属性和值之间的空格?

ruby-on-rails - Ruby on Rails 中的自定义格式

html - 动态生成的 HTML 的格式 - 没人关心吗?

text - 为什么 LaTeX 会忽略文档类中的字体大小

excel - 带硬停止的条件格式颜色渐变