我有一个要解决的任务,我想我可以使用PowerShell。
从本教程中,我发现我可以阅读一个文本文件并像这样显示它:
# C:\Users\Andrew> Get-Content -Path d:\TextToFind.txt
然后,根据另一个教程,我尝试在文本文件中搜索短语:
$Path = "D:\My Programs\2017\MeetSchedAssist\Meeting Schedule Assistant"
$Text = "ID_STR_THIS_VERSION"
$PathArray = @()
$Results = "D:\Results.txt"
# But I want to IGNORE "resource.h"
# But I want to filter for *.h AND *.cpp
Get-ChildItem $Path -Filter "*.cpp" | Where-Object { $_.Attributes -ne "Directory"}
ForEach-Object {
If (Get-Content $_.FullName | Select-String -Pattern $Text) {
$PathArray += $_.FullName
$PathArray += $_.FullName
}
}
Write-Host "Contents of ArrayPath:"
$PathArray | ForEach-Object {$_}
不起作用:
特别是,我想做的是这样的:
For each line of text in TextToFind.txt
Examine all CPP and H files in folder XXX - but ignore RESOURCE.H
If the file DOES NOT use this line of text
Append the line of text to a log file.
End If
End For
我知道编写的脚本无法做到这一点。但是我没有遇到最大的障碍。
根据评论和答案,我尝试了以下方法:
# Read in the STRINGTABLE ID values I want to locate
$TextToFind = Get-Content -Path d:\TextToFind.txt
$Path = "D:\My Programs\2017\MeetSchedAssist\Meeting Schedule Assistant"
$Text = "ID_STR_THIS_VERSION"
$PathArray = @()
$Results = "D:\Results.txt"
# But I want to IGNORE "resource.h"
# But I want to filter for *.h AND *.cpp
# First you collect the files corresponding to your filters
$files = Get-ChildItem $Path -Filter "*.cpp" | Where-Object { $_.Attributes -ne "Directory"}
# Now iterate each of these text values
$TextToFind | ForEach-Object {
$Text = $_
Write-Host "Checking for: " $Text
# Then, you enumerate these files and search for your pattern
$InstancesFound = $FALSE
$files | ForEach-Object {
If ((Get-Content $_.FullName) | Select-String -Pattern $Text) {
$PathArray += $Text + " " + $_.FullName
$InstancesFound = $TRUE
}
}
if($InstancesFound -eq $FALSE) {
$PathArray += $Text + " No instance found in the source code!"
}
}
Write-Host "Contents of ArrayPath:"
$PathArray | ForEach-Object {$_}
上面的唯一问题是,它没有考虑忽略resource.h的因素,而且我似乎无法为.h和.cpp进行过滤。
我想你想要的应该像这样:
$Path = "D:\My Programs\2017\MeetSchedAssist\Meeting Schedule Assistant"
$Text = "ID_STR_THIS_VERSION"
$PathArray = @()
$Results = "D:\Results.txt"
# But I want to IGNORE "resource.h"
# But I want to filter for *.h AND *.cpp
# First you collect the files corresponding to your filters
$files = Get-ChildItem -Path "$Path\*" -Include "*.cpp", "*.h" | Where-Object { $_.Attributes -ne "Directory"}
# Then, you enumerate these files and search for your pattern
$files | ForEach-Object {
If ((Get-Content $_.FullName) | Select-String -Pattern $Text) {
$PathArray += $_.FullName
}
}
Write-Host "Contents of ArrayPath:"
$PathArray | ForEach-Object {$_}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句