Search code examples
powershelldatetextfilenames

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?!


Solution

  • 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)