我想列印與正則運算式(Get-Content)匹配的檔案的輸出,擔心我也在使用正則運算式查找(Get-ChildItem)檔案。
-檔案示例:ITOPS_Log [2022-06-18].txt
-檔案內容:QQQ-9999999-QQQ
#Find the File using Regex:
$folder = "C:\Users\Eddy\Desktop"
$valid_files = Get-ChildItem $folder| Where-Object { $_.Name -match 'ITOPS_Log.\[\d{4}-\d{2}-\d{2}\].txt' }
Write-Output $valid_files
#Read the file and print content.
Foreach ($file in $valid_files) {
$content = (Get-Content $file.FullName)
ForEach ($line in $content) {
Write-Output "$line"
}
}
輸出:
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 22/06/2022 16:11 64 ITOPS_Log [2022-06-18].txt
Get-Content : An object at the specified path C:\Users\Eddy\Desktop\ITOPS_Log [2022-06-18].txt does not exist, or has been filtered by the -Include or -Exclude parameter.
At C:\Users\Eddy\Desktop\Itops_Log_test_V2.ps1:15 char:25
$content = (Get-Content $file.FullName)
~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : ObjectNotFound: (System.String[]:String[]) [Get-Content], Exception
FullyQualifiedErrorId : ItemNotFound,Microsoft.PowerShell.Commands.GetContentCommand
我知道如果只需要數字,我不會使用正則運算式來匹配內容。但是我已經在沒有過濾器的情況下被卡住了,我需要先解決這個問題,然后應用正則運算式來匹配數字。
如何使用此代碼列印檔案的輸出?我不明白我錯過了什么。
uj5u.com熱心網友回復:
繼續我的評論,-PathGet-ChildItem 和 Get-Content 上的引數嘗試決議通配符,因為您的檔案有方括號,它會將其視為一系列字符或數字。
為避免這種情況,請改用,-LiteralPath這樣路徑中的任何內容都不會被解釋。
然后為了測驗檔案在方括號內是否有類似日期的內容,我將在檔案的 BaseName 屬性上使用錨定正則運算式:
#Find the File using Regex:
$folder = "C:\Users\Eddy\Desktop"
$valid_files = Get-ChildItem -LiteralPath $folder -Filter 'ITOPS_Log*.txt' -File |
Where-Object { $_.BaseName -match '\[\d{4}-\d{2}-\d{2}\]$' }
# show the found files on screen
$valid_files
#Read the file and print content.
foreach ($file in $valid_files) {
$content = (Get-Content -LiteralPath $file.FullName)
foreach ($line in $content) {
Write-Host $line
# or just the number?
Write-Host ([regex]'(\d )').Match($line).Groups[1].Value
}
}
檔案 BaseName 的正則運算式詳細資訊(--> 不帶擴展名的檔案名):
\[ Match the character “[” literally
\d Match a single digit 0..9
{4} Exactly 4 times
- Match the character “-” literally
\d Match a single digit 0..9
{2} Exactly 2 times
- Match the character “-” literally
\d Match a single digit 0..9
{2} Exactly 2 times
\] Match the character “]” literally
$ Assert position at the end of the string (or before the line break at the end of the string, if any)
uj5u.com熱心網友回復:
#Find the File using Regex:
$folder = "C:\Users\Eddy\Desktop"
$valid_files = Get-ChildItem $folder| Where-Object { $_.Name -match 'ITOPS_Log.\[\d{4}-\d{2}-\d{2}\].txt' }
Write-Output $valid_files
Write-Output $valid_files
#Read the file and print content.
Foreach ($file in $valid_files) {
$content = (Get-Content -LiteralPath $folder\$file)
ForEach ($line in $content) {
Write-Output "$line"
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/495215.html
