0

I want to search a textfile for more than one string. If i find at least 1 string ( i repeat , i only need one string to be found, not all of them ) i want the program to stop and create a file in which i will find the text : "found" This is my code that doesn't work properly :

$f = 'C:\users\datboi\desktop\dump.dmp'

$text = 'found'

$array = "_command",".command","-
command","!command","+command","^command",":command","]command","[command","#command","*command","$command","&command","@command","%command","=command","/command","\command","command!","command@","command#","command$","command%","command^","command&","command*","command-","command+","command=","command\","command/","command_","command.","command:"

$len    = 9
$offset = 8

$data = [IO.File]::ReadAllBytes($f)


for ($i=0; $i -lt $data.Count - $offset; $i++) {
$slice = $data[$i..($i+$offset)]
$sloc = [char[]]$slice

  if ($array.Contains($sloc)){
    $text > 'command.log'
    break 
}
}

When i say it doesn t work properly i mean : it runs, no errors, but even if the file contains at least one of the strings from the array, it doesn't create the file i want .

2 Answers 2

1

This is literally what the Select-String cmdlet was created for. You can use a Regular Expression to simplify your search. For the RegEx I would use:

[_\.-!\+\^:]\[\#\*\$&@%=/\\]command|command[_\.-!\+\^:\#\*\$&@%=/\\]

That comes down to any of the characters in the [] brackets followed by the word 'command', or the word 'command' followed by any of the characters in the [] brackets. Then just pipe that to a ForEach-Object loop that outputs to your file and breaks.

Select-String -Path $f -Pattern '[_\.-!\+\^:]\[\#\*\$&@%=/\\]command|command[_\.-!\+\^:\#\*\$&@%=/\\]' | ForEach{
    $text > 'command.log'
    break
}
Sign up to request clarification or add additional context in comments.

1 Comment

This works perfectly but it takes a lot of time for big files. Is there a faster method ?
1

First, I would recommend using a regular expression as you can greatly shorten your code.

Second, PowerShell is good at pattern matching.

Example:

$symbolList = '_\-:!\.\[\]@\*\/\\&#%\^\+=\$'
$pattern = '([{0}]command)|(command[{0}])' -f $symbolList
$found = Select-String $pattern "inputfile.txt" -Quiet
$found

The $symbolList variable is a regular expression pattern containing a list of characters you want to find either before or after the word "command" in your search string.

The $pattern variable uses $symbolList to create the pattern.

The $found variable will be $true if the pattern is found in the file.

2 Comments

This works perfectly but it takes a lot of time for big files. Is there a faster method ?
Can you be more specific?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.