Saturday, June 6, 2015

What is here-string in Windows PowerShell and how do you use it?

Here-string is a generic way of denoting a file literal or an input stream. It is used to treat a part of the source code file as a separate file. Here-string finds its origin in UNIX Shell

Like other shell programs Here-strings is also a feature of PowerShell.

Probably you be able to comprehend it better by looking at how it is used.
First of all how do you create a string from a block of text?
Let us take the Hello World example.
The Here-string variable $hello is to be declared as shown:
Hello World

It has to be declared exactly as shown.
For example if you declare it as,
$hello=@"Hello World"@

then immediately when you try to run this script you get the following error:
At line:1 char:10
$hello=@"Hello World"@
+          ~
No characters are allowed after a here-string header but before the end of the line.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedCharactersAfterHereStringHeader

Of course you will notice that the following declaration also produces an error:
Hello World"@

The error if you run this is:
The string is missing the terminator: "@.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString

Now that it is correctly declared if you run the script you get the response as

Hello World
See the response in Windows PowerShell as shown:

The point to remember is the declaration starts with @" and whatever else start on the next line
and Ends with "@ on a new line. In between you can have strings, variables, formatted text etc.


No comments: