Rupesh
Rupesh

Reputation: 95

PowerShell format TimeStamp with Custom Message appended

Novice to PowerShell. Trying basic examples.

I'm trying to append TimeStamp to a Custom Message while writing information to log file.

function Get-TimeStamp {
    return Get-Date -Format yyyymmdd_hhmmss
}
write-host '[INFO].['$(Get-TimeStamp)'] Message'

The output comes as below:

[INFO].[  20184827_054844 ] Message

Can someone please point out me in getting rid of the extra spaces before and after timestamp?

Upvotes: 0

Views: 393

Answers (2)

CodeNagi
CodeNagi

Reputation: 419

In addition to Rupesh's answer- It is giving you extra spaces because it's how powershell unravels or expand the subexpression which you are concatenating and writing to host

Other ways to do what you want are presented below: With "+" string concatenation operator

write-host ('[INFO].['+$(Get-TimeStamp)+'] Message')
---> [INFO].[20183327_033349] Message

See related question and info here:

How do I concatenate strings and variables in PowerShell?

Windows Powershell Language Specification Ver 3.0 Starting page 21

Upvotes: 0

Rupesh
Rupesh

Reputation: 95

Just got it by doing basic Googling

I just needed to enclose contents in Double Quotes

write-host "[INFO].[$(Get-TimeStamp)] Message"

Upvotes: 1

Related Questions