Micky
Micky

Reputation: 33

Create file with date and time stamp in Powershell

I would like to create a file whose name is the current time. i've tried this code below but it's not working :

$Currentpath = split-path -parent $MyInvocation.MyCommand.Definition 
$FileLogdate = Get-Date -format 'dd/MM/yyyy HH:mm:ss'
Write-Host($FileLogdate) 

New-Item -Path $Currentpath -Name "$FileLogdate" -ItemType "file"

Upvotes: 1

Views: 21314

Answers (3)

Adi Bnaya
Adi Bnaya

Reputation: 511

You cannot create a file with / or : in its name, you should parse the name you created in $FileLogdate and replace the / and : with . or _

For example try to change your 2nd line to this:

$FileLogdate = Get-Date -format 'dd.MM.yyyy HH_mm_ss'

Upvotes: 3

henrycarteruk
henrycarteruk

Reputation: 13237

As has been mentioned already, the issue is the special chars that aren't allowed in filenames.

I would also use a different format of your date, reverse the date format so that it starts with year:

Get-Date –format 'yyyyMMdd_HHmmss'

This way if there are more than one file named this way, they will sort nicely in chronological order in a folder view

Upvotes: 6

Stuart
Stuart

Reputation: 6780

Surround your Get-Date with parentheses, like so:

(Get-Date -f yyyy-MM-dd_HH-mm-ss)

So:

$Currentpath = split-path -parent $MyInvocation.MyCommand.Definition 
$FileLogdate = (Get-Date -f yyyy-MM-dd_HH-mm-ss)
Write-Host($FileLogdate) 
# Outputs: 2019-02-25_08-02-25

New-Item -Path $Currentpath -Name "$FileLogdate" -ItemType "file"

Upvotes: -1

Related Questions