#PowershellBasics: Adding data to a string using subexpressions.
7October 14, 2021 by Kenneth Fisher
I’m working on a project right now where I want to add the date/time to the end of a filename. It didn’t take me long before I found a solution, and that solution lead me to subexpressions.
$Path = "C:\temp\"
"$($Path)RunThisScript_$(get-date -f yyyyMMdd_hhmmss).sql"
Basically a subexpression looks like this $(). Whatever is in the parenthesis gets put into the string. I’m doing it twice here. I’m starting with RunThisScript.sql and first I add in my path variable, the next adds a formatted date/time string with the end result of:
C:\temp\RunThisScript_20211005_112552.sql
I have to admit, I really like this. It feels a lot cleaner than what I’d have to do in SQL Server.
DECLARE @Path varchar(50) = 'C:\Temp\'
PRINT @Path + 'RunThisScript'+format(getdate(),'yyyyMMdd_hhmmss')+'.sql'
The Powershell code looks cleaner than doing this with T-SQL! Powershell is one of those things I always want to use more but old habits die hard.
Right there with you on all points.
Here is another way..
$Path = ‘C:\http://gravatar.com/ad516503a11cd5ca435acc9bb6523536Temp\’
[string]::Format(“{0}{1}.sql”, $Path, (get-date -f yyyyMMdd_hhmmss))
Or, a little more complex example where a referenced string is referenced more than once…
$Path = ‘C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\Backup’
[string]::Format(“{0}\{1}\{1}{2}.bak”, $Path, ‘MyDatabase’, (get-date -f yyyyMMdd_hhmmss))
Very nice. That’s useful stuff 🙂
FYI, powershell supports format strings directly, so you don’t need to use the [string] class to do it:
“`
$Path = ‘C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\Backup’
‘{0}\{1}\{1}{2}.bak’ -f $Path, ‘MyDatabase’, (Get-Date -f yyyyMMdd_HHmmss)
“`
Also, in case this wasn’t a typo, I’d recommend using uppercase HH so you use the 24-hour part.
Nice post! This is sort of unrelated, but it’s something I learned recently, so figured I would share…when referencing a variable in an interpolated string, instead of having to use
[powershell]
$variable = 1234;
write “$($variable)”
[/powershell]
You can use:
[powershell]
$variable = 1234;
write “${variable}”
[/powershell]
I’ve found it a little easier to read this way.
[…] Kenneth Fisher shows us how Powershell implements subexpressions: […]