Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including current date in file name

Tags:

powershell

How do I include the date after base name of the file? When the PowerShell script below is executed, it will download the csv to the destination folder from the website:

$client = new-object System.Net.WebClient
$client.DownloadFile("https://files.docparser.com/d/jvmnvggcccfxz","C:\test\IV_1.csv")

The output file name is IV_1.csv.

How do I add the date to the filename? For example filename, IV_1-04-04-2020.csv.

like image 947
Ted.Xiong Avatar asked Dec 10 '25 21:12

Ted.Xiong


2 Answers

You could get the current date string with ToString("dd-MM-yyyy") from Get-Date, extract the filename and extension with System.IO.Path.GetFileNameWithoutExtension() and System.IO.Path.GetExtension(), then format all the parts together with the -f Format operator.

$file = "IV_1.csv"

$dateString = (Get-Date).ToString("dd-MM-yyyy")

$filename = [System.IO.Path]::GetFileNameWithoutExtension($file)

$extension = [System.IO.Path]::GetExtension($file)

"{0}-{1}{2}" -f $filename, $dateString, $extension

Output:

IV_1-05-04-2020.csv

However, if your dealing with full paths, then GetFileNameWithoutExtension will not preserve the whole path, only the filename. You could use System.String.Substring() and System.String.LastIndexOf() to extract the full path without the extension. This will take everything before the last . character.

$file = "C:\test\IV_1.csv"

$dateString = (Get-Date).ToString("dd-MM-yyyy")

$path =  $file.Substring(0, $file.LastIndexOf('.'))

$extension = [System.IO.Path]::GetExtension($file)

"{0}-{1}{2}" -f $path, $dateString, $extension

Output:

C:\test\IV_1-05-04-2020.csv

We could also wrap the above into a function:

function Format-FilePathWithDate {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string]$FilePath,

        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string]$DateFormat
    )

    $dateString = (Get-Date).ToString($DateFormat)

    $path =  $FilePath.Substring(0, $FilePath.LastIndexOf('.'))

    $extension = [System.IO.Path]::GetExtension($FilePath)

    "{0}-{1}{2}" -f $path, $dateString, $extension
}

Then use this function specifically in your scenario:

$client = new-object System.Net.WebClient

$file = Format-FilePathWithDate -FilePath "C:\test\IV_1.csv" -DateFormat "dd-MM-yyyy"

$client.DownloadFile("https://files.docparser.com/d/jvmnvggcccfxz", $file)
like image 178
RoadRunner Avatar answered Dec 13 '25 08:12

RoadRunner


Insert the date like this:

$client = new-object System.Net.WebClient
$client.DownloadFile("https://files.docparser.com/d/jvmnvggcccfxz","C:\test\IV_1-$((Get-Date).ToString('dd-MM-yyy')).csv")
like image 39
stackprotector Avatar answered Dec 13 '25 08:12

stackprotector