Date of file name from variable

This topic contains 3 replies, has 3 voices, and was last updated by Profile photo of Dmitry P Dmitry P 1 year, 9 months ago.

  • Author
    Posts
  • #30177
    Profile photo of Dmitry P
    Dmitry P
    Participant

    Hi all! A newbie question, perhaps, but I didn't found a solution about that. The code is:
    `
    $date = Get-Date -DisplayHint Date
    New-Item -ItemType file "D:\$($date).txt"
    `
    And ISE says, that's given path format is unsupported. Why so and how make it work?

  • #30179
    Profile photo of Geraldo Quezada
    Geraldo Quezada
    Participant

    Dmitry,

    I am also a newbie. You will need to convert the date to a string to create the file:

    $date = (Get-Date -DisplayHint Date).ToString("D")
    New-Item -ItemType File "D:\$date.txt"

  • #30180
    Profile photo of Curtis Smith
    Curtis Smith
    Participant

    It's because filenames do not support the ":" or "/" characters.

    $date = Get-Date -DisplayHint Date
    "F:\$($date).txt"
    New-Item -ItemType file "F:\Temp\$($date).txt"
    

    Results:

    F:\09/28/2015 08:51:22.txt
    New-Item : The given path's format is not supported.
    At line:3 char:1
    + New-Item -ItemType file "F:\Temp\$($date).txt"
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [New-Item], NotSupportedException
        + FullyQualifiedErrorId : System.NotSupportedException,Microsoft.PowerShell.Commands.NewItemCommand
    

    Use this:

    $date = Get-Date -Format "D"
    "F:\$($date).txt"
    New-Item -ItemType file "F:\Temp\$($date).txt"
    
  • #30206
    Profile photo of Dmitry P
    Dmitry P
    Participant

    Thanks, Juan! It's what I looked for.

You must be logged in to reply to this topic.