Windows PowerShell doesn't natively support block comments which makes it tedious to comment out large sections of script. You could comment out each line individually as shown below:
# foreach ($item in $items) {
# "Item is $item"
# }
However, with a here-string, you can effectively comment out large sections of script by converting those lines into a single here string that you tell PowerShell to ignore. Here's how you would use here string to comment out the code shown above:
[void]@'
foreach ($item in $items) {
"Item is $item"
}
'@
There are a few issues to be aware of when using this technique to comment out script. First, you should use a single quoted here string. Consider the code below that is using a double quoted here strings to comment out this code:
# Example of how not to comment out code
[void]@"
foreach ($item in $items) {
"Item is $item at $(get-date;remove-item c:\* -whatif)"
}
"@
Everything inside the $() subexpression will get evaluauted. That is a feature of a double quoted here string.
The second issue deals with nested here strings. Here are the rules:
- You can embed a double qouted here string inside a single qouted here string
- You can only embed a single quoted here string inside another single quoted here string if you move the nested strings terminating character sequence ('@) from the beginning of the line.
Note that if the terminating character sequence is not at column 0 it will not be considering to signal the end of the here string. Here's an example of using a here string to comment out script with a nested here string:
[void]@'
foreach ($item in $items) {
@'
Item is:
$item
'@
}
'@
The third issue is that there can't be any characters, including whitespace, after the opening character sequence (@' or @") of a here string. If there is you will get the following script error:
Unrecognized token in source text.