![](/img/trans.png)
[英]How to find a specific text block in a log file using PowerShell and RegExp?
[英]How to create an empty log or text file with Powershell using date or timestamp?
如何使用 powershell 創建一個空文件,類似於 Linux 上的“觸摸”,文件名中帶有時間戳?
與以下沒有太大區別:
md5sum /etc/mtab > "$(date +"%Y_%m_%d_%I_%M_%p").log"
盡管該文件實際上不是空的,但它確實將日期合並到文件名本身中。
對 Powershell 的嘗試:
PS /home/nicholas/powershell/file_ops> New-Item -ItemType file foo.txt
New-Item: The file '/home/nicholas/powershell/file_ops/foo.txt' already exists.
New-Item: The file '/home/nicholas/powershell/file_ops/foo.txt' already exists.
PS /home/nicholas/powershell/file_ops> New-Item -ItemType file bar.txt
Directory: /home/nicholas/powershell/file_ops
Mode LastWriteTime Length Name
---- ------------- ------ ----
----- 12/20/2020 10:56 AM 0 bar.txt
PS /home/nicholas/powershell/file_ops> $logfile = "./"+$FN+"-LOG-AddUser_$(get-date -Format yyyymmdd_hhmmtt).txt"
理想情況下,生成任意數量的空日志或文本文件。
也可以看看:
https://community.spiceworks.com/topic/1194231-powershell-adding-a-variable-into-a-log-filename
https://superuser.com/q/502374/977796
https://4sysops.com/archives/understanding-the-powershell-_-and-psitem-pipeline-variables/
在最簡單的情況下,如果要無條件創建文件,請使用New-Item -Force
- 但請注意,如果目標文件存在,則其內容將被丟棄:
# CAVEAT: Truncates an existing file. `-ItemType File` is implied.
# * Outputs a [System.IO.FileInfo] instance describing the new file, which
# $null = ... discards here.
# * `Get-Date -UFormat` allows you to perform Unix-style date formatting.
$null = New-Item -Force "$(Get-Date -UFormat "%Y_%m_%d_%I_%M_%p").log"
New-Item
(位置隱含)的-Path
參數支持路徑數組,因此您可以一次傳遞多個路徑。
默認情況下,會創建一個空文件,但您可以選擇通過-Value
參數提供(初始)內容。
如果您真的想模擬touch
Unix 實用程序的行為,則需要做更多工作,默認情況下,這意味着(請注意, touch
支持多種選項[1] ):
$file = "$(Get-Date -UFormat "%Y_%m_%d_%I_%M_%p").log"
# Trick: This dummy operation leaves an existing file alone,
# but creates the file if it doesn't exist.
Add-Content -LiteralPath $file -Value $null
(Get-Item -LiteralPath $file).LastWriteTime = Get-Date
筆記:
以上僅限於由文字路徑指定的單個文件,並且不包括錯誤處理。
請參閱此答案以了解自定義 PowerShell function Touch-File
,它以 PowerShell 慣用方式實現了touch
實用程序的大部分功能,包括正確處理通配符模式的能力。
所述 function也可作為MIT 許可的 Gist 獲得。 假設您已經查看了鏈接代碼以確保它是安全的(我可以親自向您保證,但您應該始終檢查),您可以直接安裝它,如下所示:
irm https://gist.github.com/mklement0/82ed8e73bb1d17c5ff7b57d958db2872/raw/Touch-File.ps1 | iex
[1] 鏈接頁面是touch
的 POSIX 規范,它要求最少的功能; 具體的實現可能支持更多。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.