TimeStamp on file name using PowerShell

前端 未结 5 686
甜味超标
甜味超标 2020-12-07 13:18

I have a path in a string,

\"C:\\temp\\mybackup.zip\"

I would like insert a timestamp in that script, for example,

\"C:\\temp\\myb

相关标签:
5条回答
  • 2020-12-07 13:32

    You can insert arbitrary PowerShell script code in a double-quoted string by using a subexpression, for example, $() like so:

    "C:\temp\mybackup $(get-date -f yyyy-MM-dd).zip"
    

    And if you are getting the path from somewhere else - already as a string:

    $dirName  = [io.path]::GetDirectoryName($path)
    $filename = [io.path]::GetFileNameWithoutExtension($path)
    $ext      = [io.path]::GetExtension($path)
    $newPath  = "$dirName\$filename $(get-date -f yyyy-MM-dd)$ext"
    

    And if the path happens to be coming from the output of Get-ChildItem:

    Get-ChildItem *.zip | Foreach {
      "$($_.DirectoryName)\$($_.BaseName) $(get-date -f yyyy-MM-dd)$($_.extension)"}
    
    0 讨论(0)
  • 2020-12-07 13:32

    I needed to export our security log and wanted the date and time in Coordinated Universal Time. This proved to be a challenge to figure out, but so simple to execute:

    wevtutil export-log security c:\users\%username%\SECURITYEVENTLOG-%computername%-$(((get-date).ToUniversalTime()).ToString("yyyyMMddTHHmmssZ")).evtx
    

    The magic code is just this part:

    $(((get-date).ToUniversalTime()).ToString("yyyyMMddTHHmmssZ"))
    
    0 讨论(0)
  • 2020-12-07 13:40

    Use:

    $filenameFormat = "mybackup.zip" + " " + (Get-Date -Format "yyyy-MM-dd")
    Rename-Item -Path "C:\temp\mybackup.zip" -NewName $filenameFormat
    
    0 讨论(0)
  • 2020-12-07 13:44

    Here's some PowerShell code that should work. You can combine most of this into fewer lines, but I wanted to keep it clear and readable.

    [string]$filePath = "C:\tempFile.zip";
    
    [string]$directory = [System.IO.Path]::GetDirectoryName($filePath);
    [string]$strippedFileName = [System.IO.Path]::GetFileNameWithoutExtension($filePath);
    [string]$extension = [System.IO.Path]::GetExtension($filePath);
    [string]$newFileName = $strippedFileName + [DateTime]::Now.ToString("yyyyMMdd-HHmmss") + $extension;
    [string]$newFilePath = [System.IO.Path]::Combine($directory, $newFileName);
    
    Move-Item -LiteralPath $filePath -Destination $newFilePath;
    
    0 讨论(0)
  • 2020-12-07 13:49

    Thanks for the above script. One little modification to add in the file ending correctly. Try this ...

    $filenameFormat = "MyFileName" + " " + (Get-Date -Format "yyyy-MM-dd") **+ ".txt"**
    
    Rename-Item -Path "C:\temp\MyFileName.txt" -NewName $filenameFormat
    
    0 讨论(0)
提交回复
热议问题