TAL
TAL

Reputation: 17

Convert (Get-Date) into Text, to use it for Filenames in Powershell

Hello my helpful fiends,

i have a problem (again) ... yeah.

I want to set a fix date (at the beginning of my script) and use this fix date in different folder- and csv-file-names.

$Date = '{0:yyyyMMdd_hh:mm:ss}' -f (Get-Date)
Write-Host "The script was started $Date"

=CODE=

#Version 1
$fileOut = Join-Path -Path $path -ChildPath ("$Date.csv")
$csv| Export-Csv -Path $fileOut -Delimiter ";" -NoTypeInformation

#Result: No csv-file is written

The part that makes me angry is, that if i say $date = "TEXT" it works ...

$Date = "TEXT"
Write-Host "The script was started $Date"

$fileOut = Join-Path -Path $tsvEingang -ChildPath ("$Date.csv")
$MosaicSummary | Export-Csv -Path $fileOut -Delimiter "`t" -NoTypeInformation

#Result: The writtens csv-file-name is TEXT.csv

So how can i convert the Date into an usable text?!

Upvotes: -1

Views: 945

Answers (2)

dwillits
dwillits

Reputation: 313

Dashes are perfectly acceptable in file names however, so if you need some kind of separator, try something like this:

    $Date = '{0:yyyy-MM-dd-hhmmss}' -f (Get-Date)

Upvotes: 1

Daniel Björk
Daniel Björk

Reputation: 2507

What you normally do is remove everything that is not a number from the datetime.

$Date = '{0:yyyyMMddhhmmss}' -f (Get-Date)

That will give you something like this:

20200806024229

Which is a valid filename/foldername. Having a : (colon) in your filename is not allowed.

Upvotes: 1

Related Questions