How to create a folder using a name based on the current date in Powershell?

ashish g picture ashish g · Oct 29, 2012 · Viewed 12.6k times · Source

I have around 50 xml files that are newly generated everytime I run a particular logic. Now I want these 50 files to be stored inside a particular date-time folder. No matter how many times ever I run that logic for one particular date, the xml files should be overwritten for that particular date only (based on the hhmmss). In simple , How to create a folder using a name based on the current date and store the xml files in them depending on the date?

For Eg: there are 3 xml files file_1.xml, file_2.xml and file_3.xml

Now I want a folder to be created in the format-

**xml_yyyymmdd_hhmmss** 

that would house all the xml files in them.

For Eg: Xml_20121029_180912 

would be the folder created for today's date. And all the 3 xml files will be stored in this for today.

For tomorrow the folder name would be:

Xml_20121030_170912 

My code looks like below:

$location = New-Item -Path . -ItemType Directory -Name ("XML_$(Get-Date -f dd_MM_yyyy_hhmmss)")
$rptdir = "C:\Test" 
$ rptdir = ($rptdir + '\' + $location.Name)
$outputFile= "$rptdir\File_2.xml"
$row = "\\shared\Data\DevSB\CS\appSomeSystem.dll"   
& /f:$row /o:$outputFile

Output Error: Could not find part of the path "C:\test\XML_29_10_2012_091717\File2.xml.

The issue here is- The folder XML_29_10_2012_091717 is created with File2.xml in it but not inside the C:\Test but where the script is.

I need XML_29_10_2012_091717 to be created in C:\test with File2.xml inside it.

Environment: Win Xp Professional.

Any help would be greatly appreciated.

Thanks

Answer

CB. picture CB. · Oct 29, 2012

Try this:

New-Item -Path . -ItemType Directory -Name ("XML_$(Get-Date -f ddMMyyyy_hhmmss)")

Edit after comments:

try changing this:

$location = New-Item -Path c:\test -ItemType Directory -Name ("XML_$(Get-Date -f dd_MM_yyyy_hhmmss)")
$outputFile= "$($location.fullname)\File_2.xml"