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?
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.
Cmdlet. Rename-Item cmdlet is used to rename a folder by passing the path of the folder to be renamed and target name.
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.
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'))"
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'))"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With