Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing multiple characters in a single variable

I'm working on defining a date variable, but I need the date to be able to be used as a file name. Because of that, I need to replace a few special characters grabbed by Get-Date and replace them with underscores and periods.

$date = Get-Date -Format G | foreach {$_ -replace ":", "."}

Currently, that replaces all the :'s in the datetime, but leaves /. How can I use -replace to replace multiple things?

like image 950
Sean Long Avatar asked Jun 05 '13 12:06

Sean Long


1 Answers

Put all characters you want to replace in a character group

PS> Get-Date -Format G | foreach {$_ -replace "[:\./]", "_"}
6_5_2013 3_50_44 PM

An easier way would be to use the -Format operator:

PS> Get-Date -Format 'MM_dd_yyyy HH_mm_ss tt'
06_05_2013 15_52_09 PM
like image 88
Shay Levy Avatar answered Oct 30 '22 04:10

Shay Levy