How do I find substring after using select-string in powershell? - powershell

How do I continue to get the 12345 as output?
file.txt
MyText: 12345
myscript
Get-Content file.txt | Select-String "MyText:" | Select-Object Line
Now I would like to save last five characters, how to I retreive them?

The Select-String cmdlet -Pattern parameter expects a regex - so you can get your desired output by capturing the five digits. Note that the Select-String cmdlet also takes a -Path parameter to retrieve the content of a file. This means you can omit the first Get-Content command:
(Select-String -Path .\file.txt -Pattern 'MyText: (\d{5})').Matches.Groups[1].Value

Related

Powershell Select-String not finding what I expect

I am trying to parse file paths to just get the file name and I have a regex .*\
I'll use the following
Select-String -Pattern '.*\\' -InputObject $test -NotMatch
on a file path like C:\Users\User\Desktop\test.exe and it returns blank. If I remove the -NotMatch flag it returns the entire path. I tried using a regex tester so I know the regex is correct. What am I doing wrong?
Instead of using Select-String, use Split-Path -leaf.
Looks like -notmatch just ignores the whole line if there's a match. How about this? This is any number of characters that are not backslashes at the end of a line.
'C:\Users\User\Desktop\test.exe' | select-string [^\\]*$ | % matches | % value
test.exe

simple PowerShell Select-String Pattern

Why doesn't the PowerShell script
Get-NetRoute | Select-String -Pattern "255"
Get-NetRoute | Select-String -Pattern 255
Get-NetRoute | Select-String -Pattern '255'
Get-NetRoute | Select-String -Pattern '.*255.*'
give any result? Whats wrong with the Pattern?
The Select-String cmdlet is designed to work on string objects. The output of a Get-NetRoute cmdlet is an array.
For your code to work, you would have to convert it to a string object like this.
(Get-NetRoute | out-string).split("`n") | Select-String -Pattern "255"
But I doubt it would be very helpful if you intend to use the results down the lane.
What you really need is Where-object.
Get-NetRoute | Where-Object {$_.DestinationPrefix -like "*255*"}. Hope that helps.
Select-String will interpret Get-NetRoute as a single string (the output is a single object), so you need to split it up using the -Stream switch. Note that ipconfig | select-string would not have the same problem as it is a DOS command and so by default PowerShell will split it per line, but for PowerShell commands you need to do this when you want to do line by line interrogation since the pipeline is passing a single object, so you are doing it right to use Select-String, but just have to understand how it interprets input from the pipeline and then it'll work fine:
Get-NetRoute | Out-String -Stream | Select-String -Pattern "255"

Extract lines matching a pattern from all text files in a folder to a single output file

I am trying to extract each line starting with "%%" in all files in a folder and then copy those lines to a separate text file. Currently using this code in PowerShell code, but I am not getting any results.
$files = Get-ChildItem "folder" -Filter *.txt
foreach ($file in $files)
{
if ($_ -like "*%%*")
{
Set-Content "Output.txt"
}
}
I think that mklement0's suggestion to use Select-String is the way to go. Adding to his answer, you can pipe the output of Get-ChildItem into the Select-String so that the entire process becomes a Powershell one liner.
Something like this:
Get-ChildItem "folder" -Filter *.txt | Select-String -Pattern '^%%' | Select -ExpandProperty line | Set-Content "Output.txt"
The Select-String cmdlet offers a much simpler solution (PSv3+ syntax):
(Select-String -Path folder\*.txt -Pattern '^%%').Line | Set-Content Output.txt
Select-String accepts a filename/path pattern via its -Path parameter, so, in this simple case, there is no need for Get-ChildItem.
If, by contrast, you input file selection is recursive or uses more complex criteria, you can pipe Get-ChildItem's output to Select-String, as demonstrated in Dave Sexton's helpful answer.
Note that, according to the docs, Select-String by default assumes that the input files are UTF-8-encoded, but you can change that with the -Encoding parameter; also consider the output encoding discussed below.
Select-String's -Pattern parameter expects a regular expression rather than a wildcard expression.
^%% only matches literal %% at the start (^) of a line.
Select-String outputs [Microsoft.PowerShell.Commands.MatchInfo] objects that contain information about each match; each object's .Line property contains the full text of an input line that matched.
Set-Content Output.txt sends all matching lines to single output file Output.txt
Set-Content uses the system's legacy Windows codepage (an 8-bit single-byte encoding - even though the documentation mistakenly claims that ASCII files are produced).
If you want to control the output encoding explicitly, use the -Encoding parameter; e.g., ... | Set-Content Output.txt -Encoding Utf8.
By contrast, >, the output redirection operator always creates UTF-16LE files (an encoding PowerShell calls Unicode), as does Out-File by default (which can be changed with -Encoding).
Also note that > / Out-File apply PowerShell's default formatting to the input objects to obtain the string representation to write to the output file, whereas Set-Content treats the input as strings (calls .ToString() on input objects, if necessary). In the case at hand, since all input objects are already strings, there is no difference (except for the character encoding, potentially).
As for what you've tried:
$_ inside your foreach ($file in $files) refers to a file (a [System.IO.FileInfo] object), so you're effectively evaluating your wildcard expression *%%* against the input file's name rather than its contents.
Aside from that, wildcard pattern *%%* will match %% anywhere in the input string, not just at its start (you'd have to use %%* instead).
The Set-Content "Output.txt" call is missing input, because it is not part of a pipeline and, in the absence of pipeline input, no -Value argument was passed.
Even if you did provide input, however, output file Output.txt would get rewritten as a whole in each iteration of your foreach loop.
First you have to use
Get-Content
in order to get the content of the file. Then you do the string match and based on that you again set the content back to the file. Use get-content and put another loop inside the foreach to iterate all the lines in the file.
I hope this logic helps you
ls *.txt | %{
$f = $_
gc $f.fullname | {
if($_.StartWith("%%") -eq 1){
$_ >> Output.txt
}#end if
}#end gc
}#end ls
Alias
ls - Get-ChildItem
gc - Get-Content
% - ForEach
$_ - Iterator variable for loop
>> - Redirection construct
# - Comment
http://ss64.com/ps/

Pipe to Out-GridView and Out-File got different rows?

The following command returns only one row (the parameter -Context 10 is ignored.)
select-string -path file.txt -pattern "..." -Context 10 | Out-GridView
However, the following command create a file with all the lines.
select-string -path file.txt -pattern "..." -Context 10 | Out-File file2
Why there is a difference?
This is because Out-Gridview consumes the entire MatchInfo object that Select-String outputs, and displays all of the properties of that object as columns. Out-File on the other hand basically performs the ToString() method on everything before it outputs it to a file, and for that kind of object when it converts to a string it outputs the line, and the context lines as well. If you want Out-GridView to do that you will have to pipe to Out-String and then to Out-Gridview.

Powershell - Find files that match a pattern for specific number of times

To find a simple pattern in a set of files in powershell I go
$pattern= 'mypattern'
$r= Get-ChildItem -Path "C:\.." -recurse |
Select-String -pattern $pattern | group path | select name
$r | Out-GridView
In my scenario, I have files that contain the pattern for more than one time and others that have the pattern for one time only. So I am interested in those files that contain the pattern for more than one time and not interested in the rest. Thanks
One approach for the start of what you are looking for is Select-String and Group-Object like you already have.
Select-String -Path (Get-ChildItem C:\temp\ -Filter *.txt -Recurse) -Pattern "140" -AllMatches |
Group-Object Path |
Where-Object{$_.Count -gt 1} |
Select Name, Count |
Out-GridView
This will take all the txt files in the temp directory and group them by the number of matches. -AllMatches is important as by default Select-String will only return the first match it finds on a line.
Of those groups we take the ones where the count is higher than one using Where-Object. Then we just output the file names and there counts with a Select Name,Count. Where name is the full file path where the matched text is located.
About Out-GridView
I see that you are assinging the output from Out-GridView to $r. If you want to do that you need to be sure you add the -PassThru parameter.