The purpose of the script below is to search for a given string in a particular folder. The script does not error. But the results are not correct.
If the search is done individually search for one string it works. Once the script is run in a loop if the string is found in at least 1 file I get the correct output of files containing that string.
The issue is when the code is run in a loop and the string does not appear in any file the script returns a bunch of files where the string does not exists. If I run string individually i get no results which is correct.
I set FileOut = $null in the event that maybe this variable just needed to be cleared before setting but still same issue
$a = Get-Date
write-Host $a
$SearchStrings = Get-Content "C:\Users\Someuser\Desktop\DataDumps_PS\Delete_input_2.txt"
$out_file = "C:\Users\Someuser\Desktop\DataDumps_PS\Delete5_$(get-date -f yyyyMMdd).txt"
$RootString = "E:\SSIS_packages\"
Foreach($SearchString in $SearchStrings){
Write-host $SearchString
$FileOut = $null
$FileOut = Get-ChildItem $RootString -recurse | Select-String -pattern $SearchString | group
path | Select-Object name,@{name="SearchString"; expression={
$SearchString.replace('[','').replace(']','')} }
$FileOut | Out-file -width 300 -filepath $out_file -append
}
Sameple output with loop this string "DELETE FROM dbo.PRE_GPS_Upload_Status" returns below output. Which is wrong
Name SearchString
---- ------------
E:\SSIS_packages\ENRL_ETL\EWQ_APP\File_Extract_GPS_Fallouts.dtsx DELETE FROM dbo.PRE_GPS_Upload_Status
E:\SSIS_packages\ENRL_ETL\SNP_YearlyVerification\File_Resub_Req_File_Extract.dtsx DELETE FROM dbo.PRE_GPS_Upload_Status
E:\SSIS_packages\ETL_PNDT\File_GPS_Data_Pull.dtsx DELETE FROM dbo.PRE_GPS_Upload_Status
E:\SSIS_packages\ETL_PNDT\File_GPS_Data_Pull_06072021.dtsx DELETE FROM dbo.PRE_GPS_Upload_Status
E:\SSIS_packages\ETL_PNDT\File_GPS_Data_Pull_09092019.dtsx DELETE FROM dbo.PRE_GPS_Upload_Status
E:\SSIS_packages\ETL_PNDT\File_GPS_Data_Pull_09232021.dtsx DELETE FROM dbo.PRE_GPS_Upload_Status
E:\SSIS_packages\ETL_PNDT\File_GPS_Data_Pull_11162020.dtsx DELETE FROM dbo.PRE_GPS_Upload_Status
E:\SSIS_packages\ETL_PNDT\Backup\File_GPS_Data_Pull_06.03.2019.dtsx DELETE FROM dbo.PRE_GPS_Upload_Status
E:\SSIS_packages\ETL_PNDT\Backup\File_GPS_Data_Pull_4.2.2019.dtsx DELETE FROM dbo.PRE_GPS_Upload_Status
E:\SSIS_packages\ETL_PNDT\Backup_10112019\File_GPS_Data_Pull_10112019.dtsx DELETE FROM dbo.PRE_GPS_Upload_Status
Sample output searching only 1 string (this is correct output)
Name SearchString
---- ------------
Any thoughts on this behavior?
CodePudding user response:
Your Select-String -pattern $SearchString
is likely to blame. Because -pattern
uses regular expressions to do its matching, it's probably seeing those braces [ ], and matching on something in the file. Try swapping out -pattern
for -SimpleMatch
.