Derli Campos
Derli Campos

Reputation: 21

How to insert a cmdlet into a string in powershell

Say I want to tell the time in a string, just like this

Write-Output "It's now (Get-Date)"

That doesn't seem to work, as opposed to:

$time = Get-Date
Write-Output "It's now $time"

How can I achieve the same result without resourcing it to a variable?

Upvotes: 2

Views: 2784

Answers (3)

Adam Thomason
Adam Thomason

Reputation: 1166

Write-Host "It's now" (Get-Date)

Upvotes: -1

David Martin
David Martin

Reputation: 12248

You can format it by adding an additional $ before the brackets, PowerShell will then parse that first:

Write-Output "It's now $(Get-Date)"

Upvotes: 3

Bill_Stewart
Bill_Stewart

Reputation: 24555

Two ways I can think of off the top of my head. The first way is to use the subexpression - $() - operator:

Write-Host "It is now $(Get-Date)"

The second way is to use the string formatting - -f - operator:

Write-Host ("It is now {0}" -f (Get-Date))

Note that Write-Host will appear only in the host application and can't be redirected, so I generally don't recommend it unless you have a specific reason you don't want the command's output to be redirected.

The -f operator gives some flexibility for your outputting of the date. Example:

"It is now {0:yyyy-MM-dd hh:mm:ss}" -f (Get-Date)

See Custom Date and Time Format Strings for the details on the date formatting.

Upvotes: 5

Related Questions