Blog Post

#PowershellBasics: Adding data to a string using subexpressions.

,

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:tempRunThisScript_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'

Original post (opens in new tab)
View comments in original post (opens in new tab)

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating