Powershell - forward slash inside string

17,138

This is not PowerShell doing it, but the .Net framework. / in a date format is seen as the date separator and will be replaced with the date separator set in the Windows settings. The escape for that is a backslash as you noticed.

Write-Host $([DateTime]::Now.ToString("MM\/dd yyyy"))
Share:
17,138
Lukas Kabrt
Author by

Lukas Kabrt

I started with programming as a child on the old Atari XE computer because it seemed like an amazing adventure and 20 years later I still feel the same. I have tried various programming languages, the traditional ones - BASIC, Pascal, C++, Java, as well as the more exotic ones - LISP, Prolog but my programming language of choice is C# which I have been following since the introduction of .NET 2.0

Updated on June 04, 2022

Comments

  • Lukas Kabrt
    Lukas Kabrt almost 2 years

    As far as I know the forward slash isn't a special character in PowerShell, but in this particular situation the forward slash causes a problem.

    Write-Host $([DateTime]::Now.ToString("MM/dd yyyy"))
    

    In this case ToString ignores the custom date format (probably because it can't parse it) and outputs date in the default format.

    I know how to solve the problem - I can escape the forward slash with a backward slash "MM\/dd yyyy", but I'd like to know why it is necessary.