Home > Mobile >  Regex brings all lines. I want to make PS script to find all password pattern in File server
Regex brings all lines. I want to make PS script to find all password pattern in File server

Time:06-13

I am trying to make powershell scripts for search all documents and txt files to find Password pattern. Actually my code is working fine. My regex is capture password but it brings all lines.

Regex Pattern

""" .(?=.{8,20})(?=.[a-z])(?=.[A-Z])(?=.[0-9])(?=.[!^# $%&{()=}?-|¨@.,:;,]).* """

Samples Samples2

My regex bring all Line. How can fix this error.

PS Code

$Path = "c:\users\XXXXXXX"
$output_file = ‘C:\Users\XXXXXXXX\Desktop\Result.txt’
$ALLWORDS =Get-ChildItem $Path  -Recurse -ErrorAction SilentlyContinue

foreach ($WORDS in $ALLWORDS) { #
$Word = New-Object -ComObject Word.Application
$Word.Visible = $false
$regex = ‘\b.*(?=.{8,20})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!^# $%&{()=}?*\-|¨@.,:;,]).*\b’
$Doc = $Word.Documents.Open($WORDS.FullName, $false, $true)
$paras = $doc.Paragraphs
echo $paras.count
             
                    foreach($para in $paras){
                  if( $para.range.text -match $regex)  { 
                  $1=$matches.Values,$Words.Name | Out-File $output_file -Append
                  Write-Host $matches.Values, $words.Name 
                    }
                    }
                     
    $Doc.Close()
    $Word.Quit()
    $Word = $null
    }

CodePudding user response:

You can use

(?<!\S)(?=[^a-z\s]*[a-z])(?=[^A-Z\s]*[A-Z])(?=[^0-9\s]*[0-9])(?=\S*[!^# $%&{()=}?*|¨@.,:;,-])\S{8,20}(?!\S)

See the regex demo. Note you need to use -cmatch operator instead of -match in PowerShell, or it will be case insensitive.

Details:

  • (?<!\S) - no whitespace on the left allowed
  • (?=[^a-z\s]*[a-z]) - after any zero or more chars other than whitespace and lowercase ASCII letters, there must be a lowercase ASCII letter
  • (?=[^A-Z\s]*[A-Z]) - after any zero or more chars other than whitespace and uppercase ASCII letters, there must be an uppercase ASCII letter
  • (?=[^0-9\s]*[0-9]) - after any zero or more chars other than whitespace and ASCII digits, there must be an ASCII digit
  • (?=\S*[!^# $%&{()=}?*|¨@.,:;,-]) - after any zero or more non-whitespaces, there must be a symbol from [!^# $%&{()=}?*|¨@.,:;,-] set (replace \S* with [^\s!^# $%&{()=}?*|¨@.,:;,-]* for better performance, I just wanted to keep the pattern shorter here)
  • \S{8,20} - eight to twenty non-whitespace chars
  • (?!\S) - a right-hand whitespace boundary.
  • Related