Search This Blog

Tuesday, July 6, 2010

Using literal curly braces in "string.Format()" command

I'm developing some code to push PowerShell commands to the PowerShell runtime inside some C# .Net code and wanted to be able to use the string.Format() function to format PowerShell statements. Curly brackets are reserved both by the C# string.Format() function and PowerShell -- for their placeholder functions in C#, for use in iterative functions in PowerShell.

After trying the obvious answer and failing (using "\{" in the formatting string like in a Unix regex expression, e.g. "get-mailbox -identity {0} | %\{$_.name\}"), I tried the trick used by Transact-SQL -- doubling up on the reserved character to mark it as a literal (e.g., "get-mailbox -identity {0} | %{{$_.name}}" -- the first occurrence is a legal placeholder, the second is a literal).

That works.

No comments: