Reputation: 79
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 .
Upvotes: 0
Views: 423
Reputation: 24555
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.
Upvotes: 1
Reputation: 36297
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
}
Upvotes: 1