17

I am writing a powershell script. I would like to know how to create a folder with current date as name. The folder name should be "yyyy-MM-dd" (acording to the .NET custom format strings).

I know that to create folder I need to use this command:

New-Item -ItemType directory -Path "some path"

A possible solution could be (if I want to create the folder in the same directory as the script is:

$date = Get-Date
$date = $date.ToString("yyyy-MM-dd")
New-Item -ItemType directory -Path ".\$date"

Is there a way to chain the commands so I do not need to create the variable?

Santhos
  • 3,348
  • 5
  • 30
  • 48

5 Answers5

37

Yes.

New-Item -ItemType Directory -Path ".\$((Get-Date).ToShortDateString())"

or as alroc suggested in order to get the same formatting no matter the culture.

New-Item -ItemType Directory -Path ".\$((Get-Date).ToString('yyyy-MM-dd'))"
notjustme
  • 2,376
  • 2
  • 20
  • 27
  • 1
    Thanks, this is what I was looking for. The only problem in your solution is the short date, because it depends on users language. Please, fix it to ToString("yyyy-MM-dd") so I can accept your answer. – Santhos Sep 18 '14 at 16:22
  • Can't you move? ;) alroc posted an answer that might work for ya. For me I got exactly what you're looking for and didn't think twice about it. – notjustme Sep 18 '14 at 16:23
  • I was not sure about the "" and '' and I would like to mark your question as correct. – Santhos Sep 18 '14 at 16:29
  • I found out that you can also directly get the string from get-date like this: Get-Date -Format "yyyy-MM-dd" – Santhos Sep 19 '14 at 09:09
14

Don't use ToShortDateString() as @notjustme wrote; its formatting is dependent upon locale and your date format settings in the Regional & Language control panel. For example, on my PC right now, that would produce the following directory name:

C:\Users\me\09\18\2014

Explicitly set the format of the date string instead.

New-Item -ItemType Directory -Path ".\$((Get-Date).ToString('yyyy-MM-dd'))"
alroc
  • 27,574
  • 6
  • 51
  • 97
4
$folderName = (Get-Date).tostring("dd-MM-yyyy-hh-mm-ss") 
New-Item -ItemType Directory -Path "E:\parent" -Name $FolderName

It is creating folder with name 11-06-2020-07-29-41 under E:\parent

1

The shorter way is

$date = get-date -Format yyyy-MM-dd

TdrFlp
  • 54
  • 1
  • 6
ps4sure
  • 11
  • 1
0
$datecurrent = get-date -Format dd-MM-yy

New-Item -ItemType directory -Path ".\$datecurrent"
Wasif
  • 14,755
  • 3
  • 14
  • 34