Powershell: using regex to retrieve substrings from text/file - regex

I have a bunch of log files which should be parsed and some info from them - extracted.
A sample line (line that unfortunately, after trimming sensitive data looks like xml):
<SerialNumber>xxxxxxxxx</SerialNumber><IP>X.X.X.X</IP><UserID>user#domain.com</UserID><NumOfFiles>1</NumOfFiles><LocaleID>ENU</LocaleID><Vendor>POLYCOM</Vendor><Model>VVX311</Model><Revision>Rev-A</Revision><CurrentTime>2018-03-12T02:42:59</CurrentTime><CurrentModule><FileName>cpe.nbt</FileName><FileVersion>
I want to get ip ( in ip tags), and usermail (between userid tags)
My current "solver"
$regex = "<UserID>"
$files = Get-ChildItem -path 'c:\path\*.log'
foreach ($infile in $files) {
$res = select-string -Path $infile -Pattern $regex -AllMatches {
$txt = $res[$res.count-1]
# get user
$pos1= $txt.line.IndexOf("<UserID>")
$pos2= $txt.line.IndexOf("</UserID>")
$Puser = $txt.Line.Substring($pos1+8,$pos2-$pos1-8)
....
}
it works, but I wonder if different approach will be better, want see how this could be done with
select-string -pattern ...
Tried several "GUI" regex builders, but I can't figure how to select whats needed
Thanks
PS:
Result after
$regex = '<IP>(.*)</IP>'
$res = select-string -Path $infile -Pattern $regex
$res
0312092535|cfg |4|00|DevUpdt|[LyncDeviceUpdateC::prepareAndSendRequest] '<?xml version="1.0" encoding="utf-8"?><Request><DeviceType>3PIP</DeviceType><MacAddress>11-11-11-11-11-11</MacAddress><SerialNumber>111111111111</SerialNumber><IP>10.1.1.1</IP><UserID>user#domain.com</UserID><NumOfFiles>1</NumOfFiles><LocaleID>ENU</LocaleID><Vendor>POLYCOM</Vendor><Model>VVX311</Model><Revision>Rev-A</Revision><CurrentTime>2018-03-12T09:25:35</CurrentTime><CurrentModule><FileName>cpe.nbt</FileName><FileVersion><Major>5</Major><M
Sample of log file (100Kb+)
0312104211|nisvc|2|00|Invoker's nCommands,CurrentKey:2,(106)Responder
0312104211|nisvc|2|00|Response(-1)nisvc,(-1),(-1)app,(22),(Expiry,TransactionId,Time,Type):(-1,-1,1520844131,1)IndicationCode:(400)
0312104211|app1 |5|00|[CWPADServiceEwsRsp::execute] PAC file failed with ''
0312104301|cfg |4|00|DevUpdt|[LyncDeviceUpdateC::prepareAndSendRequest] '<?xml version="1.0" encoding="utf-8"?><Request><DeviceType>3PIP</DeviceType><MacAddress>11-11-11-11-11-11</MacAddress><SerialNumber>64167F2A8451</SerialNumber><IP>10.1.1.1</IP><UserID>user#domain.com</UserID><NumOfFiles>1</NumOfFiles><LocaleID>ENU</LocaleID><Vendor>POLYCOM</Vendor><Model>VVX311</Model><Revision>Rev-A</Revision><CurrentTime>2018-03-12T10:43:00</CurrentTime><CurrentModule><FileName>cpe.nbt</FileName><FileVersion><Major>5</Major><Minor>
0312104301|nisvc|2|00|Request(-1)nisvc,(701)NIServiceHttpReqMsgKey,(-1)proxy,(1001)AuthRsp,(Expiry,TransactionId,Time,Type):(45000,1306758696,1520844181,0)IndicationLevel:(200)

This code will get all the files, read each file line by line and create objects with a user and ip and put them in an array.
[regex]$ipUserReg = '(?<=<IP>)(.*)(?:<\/IP><UserID>)(.*)(?=<\/UserID>)'
$files = Get-ChildItem $path -filter *.log
$users = #(
foreach ($fileToSearch in $files) {
$file = [System.IO.File]::OpenText($fileToSearch)
while (!$file.EndOfStream) {
$text = $file.ReadLine()
if ($ipUserReg.Matches($text).Success -or $userReg.Matches($text).Success) {
New-Object psobject -Property #{
IP = $ipUserReg.Matches($text).Groups[1].Value
User = $ipUserReg.Matches($text).Groups[2].Value
}
}
}
$file.Close()
})
To build out my regex, I often use regexr.com, but keep in mind powershell is slightly different when it comes to certain regex.
Edit: Here is an example using select-string rather than reading line by line:
[regex]$ipUserReg = '(?<=<IP>)(.*)(?:<\/IP><UserID>)(.*)(?=<\/UserID>)'
$files = Get-ChildItem $path -filter *.log
$users = #(
foreach ($fileToSearch in $files) {
Select-String -Path $fileToSearch.FullName -Pattern $ipUserReg -AllMatches | ForEach-Object {
$_.Matches | ForEach-Object{
New-Object psobject -property #{
IP = $_.Groups[1].Value
User = $_.Groups[2].Value
}
}
}
}
)

Related

Powershell file property listing

I'm trying to collect some file properties using PowerShell within Win 2008. To do so, I've created the following script.
# BASIC PARAMETER IF NOT SET
param(
$REGEX='.*'
)
# CURRENT DATE FROM 00H
$DATAATUAL = Get-Date -Hour 0 -Minute 0 -Second 0 -Day 1 # DAY 1 FOR TESTING ONLY
# APPLICATION'S FILE PATH
$PATH = "C:\FTP\import\"
# FILE LIST WITH SELECTED FILES FROM REGULAR EXPRESSION
$FILELIST = Get-ChildItem -Path $PATH | Where-Object { ($_.LastWriteTime -ge $DATAATUAL) -and ($_.Name -cmatch "$REGEX") } | Select-Object -ExpandProperty Name
# OUTPUT IN A SORT OF CSV FORMAT
if ($FILELIST -ne $null) {
Write-Host "name;suffix;fileprocstart;filesize;filewrite"
ForEach ($FILE in $FILELIST) {
# FILE NAME PREFFIX AND SUFFIX
$FILENAME = Select-String -InputObject $FILE -CaseSensitive -Pattern "(^\d+)_($REGEX)"
# FILE TIMESTAMP CONVERTION TO EPOCH UTC-0
$FILEPROCSTART = $FILENAME.Matches.Groups[1].value
$FILEPROCSTART = [datetime]::ParseExact($FILEPROCSTART,"yyyyMMddHHmmss",$null) | Get-Date -UFormat "%s"
$FILEPROCSTART = $($FILEPROCSTART -as [long]) + 10800 # TIMEZONE CORRECTION - ADDED 3H TO BECOME UTC-0
$FILESUFFIX = $FILENAME.Matches.Groups[2].value
# FILE SIZE AND WRITE TIME
$FILESIZE = Get-ChildItem -Path $PATH -Filter $FILE | Select-Object -ExpandProperty Length
$FILEWRITE = Get-ChildItem -Path $PATH -Filter $FILE | Select-Object -ExpandProperty LastWriteTime | Get-Date -UFormat "%s"
# OUTPUT
Write-Host "$FILENAME;$FILESUFFIX;$FILEPROCSTART;$FILESIZE;$FILEWRITE"
}
}
# NO FILES FOUND
Else {
Write-Host "Empty"
}
I can start it like so:
script.ps1 -REGEX 'pattern'
It results in a list like this:
name;suffix;fileprocstart;filesize;filewrite
20220709101112_cacs1_v83.txt;cacs1_v83.txt;1657361472;5;1657397022,47321
20220709101112_cacs1_v83.txt.log;cacs1_v83.txt.log;1657361472;5;1657397041,83271
20220709101112_cacs2_v83.txt;cacs2_v83.txt;1657361472;5;1657397039,70775
20220709101112_cacs3_v83.txt.log;cacs3_v83.txt.log;1657361472;5;1657397038,03647
20220709101112_cakauto4.txt;cakauto4.txt;1657361472;5;1657397037,48906
20220709111112_coord_multicanal.txt.log;coord_multicanal.txt.log;1657365072;5;1657398468,95865
All files are generated on a daily basis and have a format similar to this:
20220709101112_cacs1_v83.txt
20220709101112_cacs1_v83.txt.log
20220709101112_cacs2_v83.txt
20220709101112_cacs3_v83.txt.log
20220709101112_cakauto4.txt
20220709101112_coord_multicanal.txt.log
Basically, the script outputs the file name, file suffix (no timestamp), file timestamp (unix format), file size and Last Write time (unix format), all in a sort of CSV format. It is meant to be started by another system to collect those properties.
It kind of works, but I can't help thinking there must be a better way to do that.
Any considerations on how to improve it?
I'm not sure if I got it right but if I understand this right:
Basically, the script outputs the file name, file suffix, file name timestamp, file size and Last Write time, all in a sort of CSV format. It is meant to be started by another system to collect those properties.
This should be all you need to start with:
$ComputerName = 'RemoteW2K8Computer'
Invoke-Command -ComputerName $ComputerName -ScriptBlock {
Get-ChildItem -Path 'C:\FTP\import' |
Select-Object -Property BaseName,Extension,Length,LastWriteTime,
#{Name = 'FileNameTimeStamp'; Expression = {($_.BaseName -split '_')[0]}}
}
Using #Olaf great tips, I've rewritten the script this way.
param($REGEX='.*')
$DATAATUAL = Get-Date -Hour 0 -Minute 0 -Second 0 -Day 1 # DAY 1 FOR TESTING ONLY
$PATH = "C:\FTP\import"
$TZ = [TimeZoneInfo]::FindSystemTimeZoneById("E. South America Standard Time")
$FILELIST = Get-ChildItem -Path $PATH |
Where-Object { ($_.LastWriteTime -ge $DATAATUAL) -and ($_.Name -cmatch "$REGEX") } |
Select-Object -Property Name,Length,
#{Name = 'Suffix'; Expression = { ($_.Name -split '_',2)[1] } },
#{Name = 'ProcStart'; Expression = {
$PROCSTART = ($_.Name -split '_')[0];
$PROCSTART = [datetime]::ParseExact($PROCSTART,"yyyyMMddHHmmss",$null);
[TimeZoneInfo]::ConvertTimeToUtc($PROCSTART, $TZ) | Get-Date -UFormat "%s";
} },
#{Name = 'FileWrite' ; Expression = {
$WRITETIME = $_.LastWriteTime;
[TimeZoneInfo]::ConvertTimeToUtc($WRITETIME) | Get-Date -UFormat "%s";
} }
if ($FILELIST -ne $null) {
Write-Host "name;suffix;procstart;filesize;filewrite"
# $FILELIST | ConvertTo-Csv -Delimiter ';' -NoTypeInformation
ForEach ($FILE in $FILELIST) {
$FILENAME = $FILE.Name
$FILESUFFIX = $FILE.Suffix
$FILESIZE = $FILE.Length
$FILEPROCSTART = $FILE.ProcStart
$FILEWRITE = $FILE.FileWrite
Write-Host "$FILENAME;$FILESUFFIX;$FILESIZE;$FILEPROCSTART;$FILEWRITE"
}
}
Else {
Write-Host "Empty"
}
As said, the output is in a CSV format.
name;suffix;procstart;filesize;filewrite
20220709101112_cacs1_v83.txt;cacs1_v83.txt;5;1657361472;1657397022,47321
20220709101112_cacs1_v83.txt.log;cacs1_v83.txt.log;5;1657361472;1657397041,83271
If I use ConvertTo-Csv (much simpler) instead of ForEach, the output would also be a CSV.
However, it places quotation marks that mess up other conversions to JSON elsewhere (maybe I can improve that later).
# $FILELIST | ConvertTo-Csv -Delimiter ';' -NoTypeInformation
"Name";"Length";"Suffix";"ProcStart";"FileWrite"
"20220709101112_cacs1_v83.txt";"5";"cacs1_v83.txt";"1657361472";"1657397022,47321"
"20220709101112_cacs1_v83.txt.log";"5";"cacs1_v83.txt.log";"1657361472";"1657397041,83271"
The other system convert it to this (I can't use ConvertTo-Json in Win2008 :-/):
{
"\"Name\"": "\"20220709101112_cacs1_v83.txt\"",
"\"Length\"": "\"5\"",
"\"Suffix\"": "\"cacs1_v83.txt\"",
"\"ProcStart\"": "\"1657361472\"",
"\"FileWrite\"": "\"1657397022,47321\""
}
Therefore, I find that writing the values with ForEach gives me a cleaner output.
Also, for fun, measuring with Measure-Command, I found that the new script is a bit faster.
The previous script takes about 24 milliseconds to complete while using a small dataset.
Now, the new one takes about 13 milliseconds with the same dataset.
All in all, a small, but good improvement, I guess.
Cheers to #Olaf for pointing to a better script and for his patience. Thank you.

PowerShell to match multiple lines with regex pattern

I write a Powershell script and regex to search two configs text files to find matches for Management Vlan. For example, each text file has two Management vlan configured as below:
Config1.txt
123 MGMT_123_VLAN
234 MGMT_VLAN_234
Config2.txt
890 MGMT_VLAN_890
125 MGMT_VLAN_USERS
Below is my script. It has several problems.
First, if I ran the script with the $Mgmt_vlan = Select-String -Path $File -Pattern $String -AllMatches then the screen output shows the expected four (4) Mgmt vlan, but in the CSV file output shows as follow
Filename Mgmt_vlan
Config1.txt System.Object[]
Config2.txt System.Object[]
I ran the script the output on the console screen shows exactly four (4) Management vlans that I expected, but in the CSV file it did not. It shows only these vlans
Second, if I ran the script with $Mgmt_vlan = Select-String -Path $File -Pattern $String | Select -First 1
Then the CSV shows as follows:
Filename Mgmt_vlan
Config1.txt 123 MGMT_123_VLAN
Config2.txt 890 MGMT_VLAN_890
The second method Select -First 1 appears to select only the first match in the file. I tried to change it to Select -First 2 and then CSV shows column Mgmt_Vlan as System.Object[].
The result output to the screen shows exactly four(4) Mgmt Vlans as expected.
$folder = "c:\config_folder"
$files = Get-childitem $folder\*.txt
Function find_management_vlan($Text)
{
$Vlan = #()
foreach($file in files) {
Mgmt_Vlan = Select-String -Path $File -Pattern $Text -AllMatches
if($Mgmt_Vlan) # if there is a match
{
$Vlan += New-Object -PSObject -Property #{'Filename' = $File; 'Mgmt_vlan' = $Mgmt_vlan}
$Vlan | Select 'Filename', 'Mgmt_vlan' | export-csv C:\documents\Mgmt_vlan.csv
$Mgmt_Vlan # test to see if it shows correct matches on screen and yes it did
}
else
{
$Vlan += New-Object -PSObject -Property #{'Filename' = $File; 'Mgmt_vlan' = "Mgmt Vlan Not Found"}
$Vlan | Select 'Filename', 'Mgmt_vlan' | Export-CSV C:\Documents\Mgmt_vlan.csv
}
}
}
find_management_vlan "^\d{1,3}\s.MGMT_"
Regex correction
First of all, there are a lot of mistakes in this code.
So this is probably not code that you actually used.
Secondly, that pattern will not match your strings, because if you use "^\d{1,3}\s.MGMT_" you will match 1-3 numbers, any whitespace character (equal to [\r\n\t\f\v ]), any character (except for line terminators) and MGMT_ chars and anything after that. So not really what you want. So in your case you can use for example this: ^\d{1,3}\sMGMT_ or with \s+ for more than one match.
Code Correction
Now back to your code... You create array $Vlan, that's ok.
After that, you tried to get all strings (in your case 2 strings from every file in your directory) and you create PSObject with two complex objects. One is FileInfo from System.IO and second one is an array of strings (String[]) from System. Inside the Export-Csv function .ToString() is called on every property of the object being processed. If you call .ToString() on an array (i.e. Mgmt_vlan) you will get "System.Object[]", as per default implementation. So you must have a collection of "flat" objects if you want to make a csv from it.
Second big mistake is creating a function with more than one responsibility. In your case your function is responsible for gathering data and after that for exporting data. That's a big no no. So repair your code and move that Export somewhere else. You can use for example something like this (i used get-content, because I like it more, but you can use whatever you want to get your string collection.
function Get-ManagementVlans($pattern, $files)
{
$Vlans = #()
foreach ($file in $files)
{
$matches = (Get-Content $file.FullName -Encoding UTF8).Where({$_ -imatch $pattern})
if ($matches)
{
$Vlans += $matches | % { New-Object -TypeName PSObject -Property #{'Filename' = $File; 'Mgmt_vlan' = $_.Trim()} }
}
else
{
$Vlans += New-Object -TypeName PSObject -Property #{'Filename' = $File; 'Mgmt_vlan' = "Mgmt Vlan Not Found"}
}
}
return $Vlans
}
function Export-ManagementVlans($path, $data)
{
#do something...
$data | Select Filename,Mgmt_vlan | Export-Csv "$path\Mgmt_vlan.csv" -Encoding UTF8 -NoTypeInformation
}
$folder = "C:\temp\soHelp"
$files = dir "$folder\*.txt"
$Vlans = Get-ManagementVlans -pattern "^\d{1,3}\sMGMT_" -files $files
$Vlans
Export-ManagementVlans -path $folder -data $Vlans```
Summary
But in my opinion in this case is overprogramming to create something like you did. You can easily do it in oneliner (but you didn't have information if the file doesn't include anything). The power of powershell is this:
$pattern = "^\d{1,3}\s+MGMT_"
$path = "C:\temp\soHelp\"
dir $path -Filter *.txt -File | Get-Content -Encoding UTF8 | ? {$_ -imatch $pattern} | select #{l="FileName";e={$_.PSChildName}},#{l="Mgmt_vlan";e={$_}} | Export-Csv -Path "$path\Report.csv" -Encoding UTF8 -NoTypeInformation
or with Select-String:
dir $path -Filter *.txt -File | Select-String -Pattern $pattern -AllMatches | select FileName,#{l="Mgmt_vlan";e={$_.Line}} | Export-Csv -Path "$path\Report.csv" -Encoding UTF8 -NoTypeInformation

Powershell Regex match and not match in a Foreach If-then not working

Hows that for a title?
I have this script Ive been working on that does two basic things: a) Use get-ntfsaccess to pull the security for a folder and then b) use the output to look up the group members of the groups that have access.
$Outfile2 = "C:\Users\local\Documents\GroupMembers.csv"
$Header2 = "GroupName,Member"
Add-Content -Value $Header2 -Path $Outfile2
$RootPath = "p:\city\Department\building"
$Folders = get-childitem2 -directory -recurse -path $RootPath
foreach ($Folder in $Folders){
$ACLs = Get-NTFSAccess $Folder.fullname
Foreach ($ACL in $ACLs){
If ($Acl.accounttype -match 'group' -and $acl.Account.accountname -notmatch '^builtin|^NT AUTHORITY\\|^Creator|^AD\\Domain')
{
$members = Get-ADGroupMember $acl.Account.accountname.TrimStart("AD\\")
}
Foreach ($member in $members) {
$OutInfo = $ACL.Account.AccountName + "," + $member.samaccountname
Add-Content -Value $OutInfo -Path $OutFile2
}
}}
Id like to be able to filter the output of get-ntfsaccess. I want to only lookup 'groups' and groups that arent the base groups (like builtin, domain admins, etc) but my match and not match arent working in the script. If I take that exact same line and run it from the prompt - it works.
PS C:\Windows\system32> $acl.Account.accountname -notmatch '^builtin|^NT AUTHORITY\\|^Creator|^AD\\Domain'
True
When run as part of the script - doesnt work. My output includes all of the domain base groups and users. Id like to also eventually add -unique to only get unique groups but this part has got me stumped....
Thanks in advance...!
I did this with success:
((dir)[0] | get-acl).access | % { $_.IdentityReference } | ? { $_ -notmatch 'builtin|nt authority' }
I cannot test with ntfsaccess at the moment but get-acl's returned IdentityReference is most likely the same field you are attempting to parse on. You might just try removing your '^'s. I also tested with "myDomain\\Domain Admins" and that worked as expected.
So I figured it out.
Three main things -
1. The Trimstart wasn't accepting the '/' no matter how i tried to 'escape' it
2. Had to use get-adgroup to pipe to get-adgroupmember
3. the IF then was script blocked wrong to write each result out at each iteration through $ACLs
$Outfile2 = "C:\Users\local\Documents\GroupMembers.csvv"
$Header2 = "GroupName,Member"
Add-Content -Value $Header2 -Path $Outfile2
$RootPath = "p:\city\Department\building"
$Folders = get-childitem2 -directory -recurse -path $RootPath
foreach ($Folder in $Folders){
$ACLs = Get-NTFSAccess $Folder.fullname
Foreach ($ACL in $ACLs){
If ($Acl.accounttype -match 'group' -and $acl.Account.accountname -notmatch '^builtin|^NT AUTHORITY\\|^Creator|^AD\\Domain')
{$members = Get-adgroup $acl.Account.accountname.substring(3) | Get-ADGroupMember
Foreach ($member in $members) {
$OutInfo = $ACL.account.AccountName + "," + $member.samaccountname
Add-Content -Value $OutInfo -Path $OutFile2
}}}}

List All Matches Found in Word Doc

I'm able to find the first match in each document that I'm searching, but am unable to list all matches found in each document when there are multiple matches. I've tried multiple ways of iterating through the matches hash table, but can't seem to get it right. Is there a way to do this?
$RX = "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.|dot|\[dot\]|\[\.\])){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
$WordFiles = Get-ChildItem $Directory -include *.doc, *.docx -recurse
$Directory = "c:\temp"
$objWord = New-Object -Com Word.Application
foreach ($fileSearched in $WordFiles) {
$objWord.Visible = $false
$objWord.DisplayAlerts = "wdAlertsNone"
$objDocument = $objWord.Documents.Open("$fileSearched")
if ($objdocument.Content.Text -match $RX){
Foreach ($found in $_.Matches) { #| ForEach-Object {$_.Value}
$file2.WriteLine("{0},{1}",$matches[$_], $filesearched.fullname)
write-host $_.matches
write-host $_.value
write-host $found
}
}
$file2.close()
}
$objWord.Quit()
Powershell's -match flavor of regex will only return the first match, and as far as I know there is no way to make it find global matches.
You can however switch to using the [regex] class matches function which matches globally by default.
([regex]::matches($objdocument.Content.Text, $RX))
UPDATE
I believe you will also need to switch $_.Matches to $_.Value per examples here.
I reviewed the link provided by cchamberlain and came up with:
$CSV = "c:\temp\output.csv"
$RX = "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.|dot|\[dot\]|\[\.\])){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
$WordFiles = Get-ChildItem $Directory -include *.doc, *.docx -recurse
$Directory = "c:\temp"
$objWord = New-Object -Com Word.Application
$file2 = new-object System.IO.StreamWriter($CSV,$true) #Append or Create a new file Stream.
$file2.WriteLine('Matches,File_Path') # write header
foreach ($fileSearched in $WordFiles) {
$objWord.Visible = $false
$objWord.DisplayAlerts = "wdAlertsNone"
$objDocument = $objWord.Documents.Open("$fileSearched")
$words = ([regex]::matches($objdocument.Content.Text,$RX) | %{$_.value})
foreach ($word in $words){
$file2.WriteLine("{0},{1}",$word, $filesearched.fullname)
}
$file2.close()
$objWord.Quit()

Why regex pattern works with html comments but doesn't work with php and js comments?

I have this problem:
Various pages of my site (tipically: html, php and js) are affected by a trojan horse (JS/Kryptik.ADZ based on NOD32 scan).
The code in each type of page is like this:
PHP:
#336988#
echo "<script type=\"text/javascript\" language=\"javascript\" > CODE OF MALWARE </script>";
#/336988#
JS:
/*336988*/
CODE OF MALWARE
/*/336988*/
HTML:
<!--336988-->
<script type="text/javascript" language="javascript" >CODE OF MALWARE</script>
<!--/336988-->
So i use Notepad++ and regex to replace malware with blank text.
My regex is this: (<!--|\#|/\*)336988.+/336988(-->|\#|\*/)
But only HTML is found by this expression. Why?
I don't understand.
I'm sorry if my english and my knowledge of regex is poor.
Thanks
Carlo
Try this one:
'^.*336988.*[\s\S]*.*336988.*$'
Today I had the same problem but with different code. This code affected aspx, asp, htdocs, html, htm and js files. Below my code in Powershell to fix these files. For JS files you need to change line:
$regex = New-Object System.Text.RegularExpressions.Regex "<!--68c8c7-->((.|\n)*)<!--/68c8c7-->"
to:
$regex = New-Object System.Text.RegularExpressions.Regex "/\*68c8c7\*((.|\n)*)68c8c7\*/"
and line
Get-ChildItem . -Recurse -Include *.aspx,*asp,*.html,*.htm | where-object {$_.lastwritetime –gt $DateToCompare} | %{Write-Host Examining file: $_.fullname; $_} | ForEach-Object { DoWork $_.Name $_.DirectoryName}
to:
Get-ChildItem . -Recurse -Include *.js | where-object {$_.lastwritetime –gt $DateToCompare} | %{Write-Host Examining file: $_.fullname; $_} | ForEach-Object { DoWork $_.Name $_.DirectoryName}
below code (this script will create Backup_* file, after all you can delete those files):
function tryFixFile($filepath, $filepathBackup)
{
$infile = [string]::join([environment]::newline, (get-content -path $filepath))
$regex = New-Object System.Text.RegularExpressions.Regex "<!--68c8c7-->((.|\n)*)<!--/68c8c7-->"
if($regex.IsMatch($infile))
{
$intAnswer = $WScriptObject.popup("File needs to be change: " + $filepath + " do you want to continue?", 0,"Change File",4)
If ($intAnswer -eq 6)
{
Write-Host " Creating backup for file: " $filepath
Copy-Item $filepath $filepathBackup
$replace = $regex.Replace($infile,"")
$replace | out-file $filepath
} else
{
$a.popup("File " + $filepath + " won't be changed.")
}
}
}
function DoWork($filename, $directory)
{
$filepath = $directory + '\' + $filename
$filepathBackup = $directory + '\' + "Backup_" + $filename
$WScriptObject = new-object -comobject wscript.shell
tryFixFile $filepath $filepathBackup
}
$pathToCheck = Read-Host 'WARNING!! Path to check/change?'
if (Test-Path $pathToCheck)
{
Set-Location $pathToCheck
#files were affected no longer that 2 days ago, you can change this
$DateToCompare = (Get-date).AddDays(-2)
Get-ChildItem . -Recurse -Include *.aspx,*asp,*.html,*.htm | where-object {$_.lastwritetime –gt $DateToCompare} | %{Write-Host Examining file: $_.fullname; $_} | ForEach-Object { DoWork $_.Name $_.DirectoryName}
}else
{
write-host "Path doesn't exist"
}
Here a script to fix 336988, 68c8c7, 8f4d8e, a59dc4.
Try this one, I had the same problem and it worked.
/#336988#(.*?)#\/336988#/ism