I'm writing a C# application which accepts, parses, and passes PowerShell commands to an internal runtime instance of PowerShell.
The preferred method for string formatting with .NET is using the "string.format" method but I quickly ran into problems with the curly brackets used both by string.format (for placeholders) and PowerShell (for loop constructs).
For instance, this command will compile but will clearly screw up:
- results = shl.RunspaceInvoke(string.Format(@"get-mailbox -identity {0} | %{$_.AcceptMessagesOnlyFromDLMembers | %{$_.DistinguishedName}}", Input1), out IErrors);
My first impulse was to remove the "@" from the string literal and escape the curly brackets but that looked simply dreadful and was too hard to debug -- the next solution which I tried, which worked was to simply double the curly brackets for anything other than string.format placeholders:
- results = shl.RunspaceInvoke(string.Format(@"get-mailbox -identity {0} | %{{$_.AcceptMessagesOnlyFromDLMembers | %{{$_.DistinguishedName}}}}", Input1), out IErrors);
This is significantly easier to read and debug.
No comments:
Post a Comment