PowerShell here-string a handy multiline string

A here-string in PowerShell is a multiline string value which keeps its formatting, works without the need of escaping doubble ( ” ) and single ( ‘ ) quotes and can be used with variables as you know it.

This short example shows you how to use a here-string within PowerShell:

1
2
3
4
5
6
7
8
9
10
11
$myVar = "string value"
 
$hereString = @"
My
    formatted
        here-string
    with a variable $myVar
and some quotes " ' " ' "
"@
 
$hereString

You can even use a here-string to add C# code to your PowerShell script as shown below:

1
2
3
4
5
6
7
8
9
10
11
12
13
Add-Type -TypeDefinition @"
    public class DoSomeMath {
        public static int Addition(int n1, int n2) {
            return n1 + n2;
        }
        public static int Subtraction(int n1, int n2) {
            return n1 - n2;
        }
    }
"@
 
[DoSomeMath]::Addition(5,2)
[DoSomeMath]::Subtraction(5,2)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.