Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create folder with current date as name in powershell

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?

like image 339
Santhos Avatar asked Sep 18 '14 16:09

Santhos


People also ask

How do I get the current date in PowerShell?

The Get-Date cmdlet gets a DateTime object that represents the current date or a date that you specify. Get-Date can format the date and time in several . NET and UNIX formats. You can use Get-Date to generate a date or time character string, and then send the string to other cmdlets or programs.

How do I rename a folder in PowerShell?

Cmdlet. Rename-Item cmdlet is used to rename a folder by passing the path of the folder to be renamed and target name.

Does mkdir work in PowerShell?

mkdir command used to create directory using cmd is also available as a function in PowerShell. PowerShell mkdir is a function defined in PowerShell to create directory and it's an alias of md command. PowerShell mkdir uses New-Item cmdlet to create directory and has the same syntax as PowerShell New-Item cmdlet.


2 Answers

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'))"
like image 135
notjustme Avatar answered Sep 17 '22 16:09

notjustme


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'))"
like image 22
alroc Avatar answered Sep 18 '22 16:09

alroc