-1

All I found online were ways to write the current date into a string using get-date.toString()

What I want to do is read the CreationDate and Time from a File and convert that into a String for a directory name.

It would suffice if i could save the different parts of CreationTime into separate Variables.

E.g.: $Year, $Month, $Day, $Hour etc.

How would I go about doing that?

Matt
  • 45,022
  • 8
  • 78
  • 119
Ollowain
  • 1
  • 1
  • 3

2 Answers2

2
$file = get-item c:\myfile.txt

$year = $file.creationtime.year
$month = $file.creationtime.month
$day = $file.creationtime.day
$hour = $file.creationtime.hour

and so on...

use $file.CreationTime | fl * for a list of available properties

CB.
  • 58,865
  • 9
  • 159
  • 159
  • Yep. No need to create the variables. The properties already exist. – Matt May 27 '15 at 13:35
  • This answer is correct, if you just skip the (unnecessary) step of setting the variables $year, $month, $day, and use the members of CreationTime instead. – Walter Mitty May 27 '15 at 13:58
2

See https://technet.microsoft.com/en-us/library/ee692801.aspx .

i.e.

(gi C:\temp\trim.csv).CreationTime.ToString('ddd MM dd yyyy')

will give you a string "Wed 05 27 2015"

UPD: or if you want to use string as a directory name just delete the spaces.

(gi C:\temp\trim.csv).CreationTime.ToString('dddMMddyyyy')

and get "Wed05272015"

Anton Z
  • 270
  • 2
  • 6
  • I belive he wanted use file creation date as directory name, so there is no need to break out the properties, i've updated my answer. – Anton Z May 27 '15 at 13:39
  • You are right. I misread the original requirement and fixated on the compromise. – Matt May 27 '15 at 13:45
  • This answer works, but I would have used the format string 'yyyy-MM-dd', and I would have saved the result in some variable like $dirname. – Walter Mitty May 27 '15 at 16:08
  • `$dirname = (gi c:\temp\file.txt).CreationTime.ToString('yyyy-MM-dd')` – Anton Z May 27 '15 at 19:41
  • This is what i was looking for. Turns out all i was mising were the single quotes in the toString statement. Thank you all for the swift replies – Ollowain May 28 '15 at 08:46