<<< Back to Search

File Management

Create Folder and File with Timestamp

Create folder and file with timestamp for a given Path+File

# Parameters
$pathFile = "C:\Temp\x1\y1\MyLog.txt"

$path = [System.IO.Path]::GetDirectoryName($pathFile)
$pathFileTimestamp = "$path\" + `
        [System.IO.Path]::GetFileNameWithoutExtension($pathFile) + "_" + `
        (get-date -format yyyyMMdd_HHmmss) + ([System.IO.Path]::GetExtension($pathFile))

# Check path and create for a given file
if(-not(Test-Path $path)){
    New-Item -Path $path -ItemType Directory -Force 
}

# Execute action with file: i.e. Create the file
New-Item -Path "$pathFileTimestamp" -ItemType File -Force -value "Test contents"

PS C:\>


    Directory: C:\Temp\x1\y1


Mode                 LastWriteTime         Length Name                                                                                             
----                 -------------         ------ ----                                                                                             
-a----          4/3/2021  10:04 AM             13 MyLog_20210403_100434.txt