Skip to content

Instantly share code, notes, and snippets.

@drlsdee
Created October 24, 2023 06:59
Show Gist options
  • Save drlsdee/70d4fa11c37757fa660328dedd0dc854 to your computer and use it in GitHub Desktop.
Save drlsdee/70d4fa11c37757fa660328dedd0dc854 to your computer and use it in GitHub Desktop.
Gets an object of type System.IO.FileInfo and returns the object with generated filename based on the old name and timestamp. May be useful for creating backups, rotating logs etc.
function Get-TimeStampedFileName {
[CmdletBinding()]
[OutputType([System.IO.FileInfo])]
param (
[Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName,Position=0)]
[Alias('FullName', 'p')]
[System.IO.FileInfo]$Path,
[Parameter(Position=1)]
[Alias('u', 'z')]
[switch]$UTC
)
begin {
[string]$patternTimeStamp = '{0:yyyy-MM-dd_HH-mm-ss}_{1}'
}
process {
if ($UTC) {
[datetime]$objTimeStamp = [datetime]::UtcNow
}
else {
[datetime]$objTimeStamp = [datetime]::Now
}
[string]$fileNameNew = [string]::Format(
$patternTimeStamp,
$objTimeStamp,
$Path.Name
)
[string]$outputPathNew = [System.IO.Path]::Combine(
$Path.DirectoryName,
$fileNameNew
)
return [System.IO.FileInfo]::new($outputPathNew)
}
end {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment