我的作業系統是Windows 10。
我有一個包含一對多 .txt 檔案的資料夾。每個文件中的行格式如下:
2016-12-07 14:08:43 7.7 b=123 r=890
我希望創建一個可以執行的可重現過程,該過程將查看資料夾中的所有文件,並為我提供包含所有文件的 .txt 文件中的文件名6.7
以及大於 7 天前的日期。
範例場景:
文件 1 包含:2016-12-07 14:08:43 7.7 b=123 r=890
文件2包含:2017-01-24 14:08:43 7.7 b=123 r=890
文件3包含:2017-01-23 14:08:43 6.7 b=123 r=890
我執行該過程並收到一個 .txt 文件,其中包含:File3
我不知道這是否可以使用命令列、PowerShell 來完成,或者是否需要全面的開發工作來完成此任務。
答案1
遵循 PowerShell 腳本
Get-ChildItem *.txt -Recurse |
ForEach-Object {
$aux=$_
Get-Content "$aux" |
ForEach-Object {
if ($_ -match '6\.7') {
if ( [datetime] $_.Substring(0,19) -gt (Get-Date).AddDays(-7)) {
$aux.FullName
}
}
}
}
或同等的 oneliner
Get-ChildItem *.txt -Recurse | ForEach-Object { $aux=$_; Get-Content "$aux" | ForEach-Object {if ($_ -match '6\.7') {if ( [datetime] $_.Substring(0,19) -gt (Get-Date).AddDays(-7)) {$aux.FullName}}}}
基本說明:
txt
取得檔案清單Get-ChildItem
並將|
結果透過管道傳輸到下一個 cmdlet- (管道式)對於每個特定文件
ForEach-Object
- 將其儲存到輔助變數
$aux=$_
(注意;
oneliner 中的尾隨分號) - 並逐行獲取其內容
Get-Content
並將|
結果通過管道傳輸到下一個 cmdlet - (管道式)對於每一個特定的行
ForEach-Object
- 測試一行是否包含
6.7
字串if ($_ -match '6\.7')
- 如果是,則測試日期(前 19 個字元)是否符合給定條件
if ( [datetime] …
- 如果是這樣,則公開文件名
$aux.FullName
- 並
{
使用一系列的close 來關閉所有的 opening}
。
答案2
擴展 JosefZ 的原始答案,我發現以下答案更完整。
在 PowerShell 檔案中包含以下內容:
$filespath = "\\sampledirectory\log\"
$outputfilename = "\\sampledirectory\log\results.txt"
########## file creation step
Get-ChildItem -Path $filespath *.txt -Recurse |
ForEach-Object {
$aux=$_
Get-Content "$aux" |
ForEach-Object {
if ($_ -match '6\.7')
{
if ( [datetime] $_.Substring(0,19) -gt (Get-Date).AddDays(-7))
{
$aux.FullName | Out-File $outputfilename -append
}
}
}
}