Using -f operator on a string that contains curly braces

萝らか妹 提交于 2019-12-30 05:56:35

问题


Consider the following here-string that I am trying to use a template for my Nagios definitions.

$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
        }

"@

I have a script that determines which of my servers are not in nagois that should be. As it loops I'm trying to have it spit out a definion for me so that I can copy and paste into my Nagios config.

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

Which nets me the following error:

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

Something like this works just fine

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

So then I found out that it is because of the other curly braces. Is there a way that i can format my string using the -f while keeping the braces? Or do i have to use variable subsitution only?


回答1:


Adding another set of curly braces seems to work:

$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'

Output:

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/using-f-operator-on-a-string-that-contains-curly-braces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!