Windows Batch Get Current Date As FileName
2024-08-15
筆記如何將當前日期作為檔案名稱,需要特別筆記的原因是因為繁體中文的日期格式需要有特殊的處理 🐸
說明
set today=%date:~0,4%%date:~5,2%%date:~8,2%
set destination=d:\home\%today%
mkdir %destination%
取得檔案資訊
🐌 Slow on Get-FileHash
Get-ChildItem -Path "D:\source" -Recurse |
Select-Object FullName,
@{Name="Size";Expression={$_.Length}},
@{Name="LastModifiedDate";Expression={$_.LastWriteTime}},
@{Name="Hash";Expression={ (Get-FileHash -Path $_.FullName).Hash }} |
Format-Table -AutoSize |
Out-File -FilePath "C:\users\ps.txt"
⚡ Quick with multi-threading to get file hash
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
namespace GetFileMetaConsole
{
class Program
{
static void Main()
{
ThreadPool.SetMinThreads(16, 16);
ThreadPool.SetMaxThreads(16, 16);
// Example list of file paths
List<string> filePaths = new List<string>();
// Read txt file line by line to filePaths
using (StreamReader reader = new StreamReader("filePaths.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
filePaths.Add(line);
}
}
// Start measuring time
Stopwatch stopwatch = Stopwatch.StartNew();
using (StreamWriter writer = new StreamWriter("result.txt"))
{
// Create tasks for each file path
List<Task<string>> tasks = new List<Task<string>>();
foreach (var filePath in filePaths)
{
tasks.Add(Task.Run(() => GetFileDetails(filePath)));
}
// Wait for all tasks to complete
Task.WaitAll(tasks.ToArray());
// Write the file details to the result file
foreach (var task in tasks)
{
writer.WriteLine(task.Result);
}
}
// Stop measuring time
stopwatch.Stop();
// Print the total time taken
Console.WriteLine($"Total time used: {stopwatch.Elapsed.TotalSeconds} seconds");
}
static string GetFileDetails(string filePath)
{
if (!File.Exists(filePath))
{
return $"File not found: {filePath}";
}
FileInfo fileInfo = new FileInfo(filePath);
// Get file size
long fileSize = fileInfo.Length;
// Get last modified date
DateTime lastModified = fileInfo.LastWriteTime;
// Get SHA256 hash
string hash;
using (FileStream stream = File.OpenRead(filePath))
{
SHA256 sha = SHA256.Create();
byte[] hashBytes = sha.ComputeHash(stream);
hash = BitConverter.ToString(hashBytes).Replace("-", "");
}
// Return details
return $"File: {filePath}\nSize: {fileSize} bytes\nLast Modified: {lastModified.ToString("yyyy/MM/dd hh:MM:ss")}\nSHA256: {hash}\n";
}
}
}