简体   繁体   English

使用 PowerShell 的文件名时间戳

[英]Timestamp on file name using PowerShell

I have a path in a string,我有一个字符串路径,

C:\temp\mybackup.zip

I would like insert a timestamp in that script, for example,我想在该脚本中插入一个时间戳,例如,

C:\temp\mybackup 2009-12-23.zip

Is there an easy way to do this in PowerShell?在 PowerShell 中有没有简单的方法来做到这一点?

You can insert arbitrary PowerShell script code in a double-quoted string by using a subexpression, for example, $() like so:您可以使用子表达式在双引号字符串中插入任意 PowerShell 脚本代码,例如 $(),如下所示:

"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的输出:

Get-ChildItem *.zip | Foreach {
  "$($_.DirectoryName)\$($_.BaseName) $(get-date -f yyyy-MM-dd)$($_.extension)"}

Here's some PowerShell code that should work.这是一些应该可以工作的 PowerShell 代码。 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;

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

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

Use:利用:

$filenameFormat = "mybackup.zip" + " " + (Get-Date -Format "yyyy-MM-dd")
Rename-Item -Path "C:\temp\mybackup.zip" -NewName $filenameFormat

If you have the path on a variable ($pathfile) use this concrete line to get the TimeStamped Path:如果您在变量 ($pathfile) 上有路径,请使用此具体行来获取时间戳路径:

(extracted from here : https://powershellexamples.com/home/Article/10/file-management-add-timestamp-to-file-name ) (从这里提取: https ://powershellexamples.com/home/Article/10/file-management-add-timestamp-to-file-name)

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


Write-Host "Path+File: $pathFile"
Write-Host "Path+File with Timestamp: $pathFileTimestamp"

Above will return:以上将返回:

PS C:\> Path+File: C:\ProgramData\MyApp\file.txt
        Path+File with Timestamp: C:\ProgramData\MyApp\file_20210328_022045.txt

Another approach for renaming.重命名的另一种方法。

Set-Location C:\Folder_containing_zipfiles
Get-ChildItem -File | ForEach-Object {  Rename-Item -Path $_.FullName -NewName  
 $_.Name.Replace('.zip',"_$(get-date -Format yyyy_MM_dd_hh_mm_ss).zip") }

Can I just add this method to add the time stamp (date) in with spaces here also (I couldn't find the solution anywhere, but thought it should be attached to this question):我可以在此处添加此方法以在空格中添加时间戳(日期)吗(我在任何地方都找不到解决方案,但认为它应该附加到这个问题上):

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

File Output: C:\temp\mybackup 2022 09 16.zip文件 Output: C:\temp\mybackup 2022 09 16.zip

Date + Filename - NOT ( Filename + Date ) - otherwise it messes up file extension. Date + Filename - 不是( Filename + Date ) - 否则会弄乱文件扩展名。

$filenameFormat = (Get-Date -Format "yyyy-MM-dd") + " " + "mybackup.zip"
Rename-Item -Path "C:\temp\mybackup.zip" -NewName $filenameFormat

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM