Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell here-string expansion

Here-strings

There are some examples regarding Powershell 'here-string' but I have hardly come across 'here-string' expansion. so I posted this to be of some help.

When you want to add some literal with line breaks, both single and double quotes do not need to be escaped and no need for line breaks like "`r`n". 'here-strings' comes to the rescue in PowerShell. They should start with

@"
and line break and should end with line break
"@

For example:                        |Result:
                                    |
@"                                  |
Hello world! 09/25/2014 11:39:56    |      Hello world! 09/25/2014 11:39:56
'(this will appear as is)'          |      '(this will appear as is)'
!                                   |      !
"@                                  |
like image 395
yantaq Avatar asked Sep 25 '14 18:09

yantaq


Video Answer


2 Answers

Here is how to introduce CmdLet and a date variable to show current date like so:
For example the following is what we want to achieve:

Hello world! 09/25/2014 11:39:56
'(this will appear as is)'
!

Here is how:

@"
Hello world! $(Get-Date)
'(this will appear as is)'
!
"@

Or with variable:

$myDate = Get-Date
@"
Hello world! ${myDate}
'(this will appear as is)'
!
"@
like image 71
yantaq Avatar answered Sep 29 '22 03:09

yantaq


This post is helpful and I landed here from looking for expanding a variable within a PowerShell here-string in a SQL query.

The following code snip will get a list of servers then loop in a Foreach-Object allowing the server name to be replaced for every query!

Thanks to @Matt for the hash-table help.

$servers = Get-Content c:\scripts\list.txt

$servers | ForEach-Object{
 $items = @{}
 $items.Server = $_

$query = @"
 WHERE svrName = $($items.Server)
"@
}
like image 21
user4317867 Avatar answered Sep 29 '22 04:09

user4317867