To check the file contents line by line - powershell

I need to check the contents line by line by selecting the string of the line.
I have declared each line matching string to a variable.Is it possible to use switch cases for looking into the variables
I have used if condition to check the each line with the help of variables .
I wanted to know whether we could use switch cases?
Consider file.txt having following contents :
$q = Get-Content -Path .\file.txt |Select-String 'Hello' -SimpleMatch
$w = Get-Content -Path .\file.txt |Select-String 'new' -SimpleMatch
$e = Get-Content -Path .\file.txt |Select-String 'World' -SimpleMatch
$r = Get-Content -Path .\file.txt |Select-String 'Hi' -SimpleMatch
$t = Get-Content -Path .\file.txt |Select-String 'greet' -SimpleMatch
So can we check the variables using the switch options. Is it possible to output the variables which are not present. How can we achieve the same if the file contents are large?
Can we use switch options and output the desired result?

If you just want to know which of the 5 words are not in any of the lines in the file, you can do this
$Pattern = 'Hello|new|World|Hi|greet'
$Test = (Get-Content -Path .\file.txt | Select-String -Pattern $Pattern -AllMatches).foreach{$_.matches.Value}
$($pattern -split '\|').where{$Test -notcontains $_}
But is that your goal?

Related

How can I use ForEach-Object output for Select-String directly?

I have several single line xml files out of which I want to extract the contents of a particular tag <LIFNR>. I managed doing that using the following two lines of power shell:
get-content P:\Webservice\21*_*CR_d*.xml | foreach-object { $_ -replace '>', ">`r`n" } > xmls_newline.txt
get-content .\xmls_newline.txt | Select-String -Pattern '.*<\/LIFNR>'
However if I want to skip the step of creating an intermediary text file I cannot achieve the same result.
$xml = get-content P:\Webservice\21*_*CR_d*.xml | foreach-object { $_ -replace '>', ">`r`n" }
$xml | Select-String -Pattern '.*<\/LIFNR>'
or
get-content P:\Webservice\21*_*CR_d*.xml | foreach-object { $_ -replace '>', ">`r`n" } | Select-String -Pattern '.*<\/LIFNR>'
each just print the result of the string splitting in the foreach-object statement, the Select-String command is ignored.
Can somebody explain to me what is different about the latter two attempts compared to the working solution?
Get-Content outputs each line as a separate string. To emulate the same behavior, split the string after > instead of appending a linebreak:
Get-Content P:\Webservice\21*_*CR_d*.xml |ForEach-Object { $_ -split '(?<=>)' } | Select-String -Pattern '.*<\/LIFNR>'
The construct (?<=...) is a lookbehind assertion - this way, PowerShell will split on a zero-length string immediately after >

How to Select-String with pattern that contains $value

How to search for a string that starts with $ in a txt file?
For example:
Get-Content $file | Select-String -pattern 'VALUE="$USERPROFILE"'
Thanks
Either use the [regex]::Escape() method to correctly escape verbatim strings for use in regex patterns:
$pattern = 'VALUE="{0}"' -f [regex]::Escape('$USERPROFILE')
Get-Content $file | Select-String -Pattern $pattern
or use the -SimpleMatch switch to indicate you don't wanna use regex at all:
Get-Content $file | Select-String -pattern 'VALUE="$USERPROFILE"' -SimpleMatch
If you only want to find strings that start with '$', you can use an approach similar to the one below.
param(
[string] $file = "$PSScriptRoot\test.txt",
[string] $pattern = "$*"
)
$stringsBeginningWithPattern = (Get-Content $file).Split() | Where-Object {
$_ -like $pattern
}
$stringsBeginningWithPattern

use powershell to grep through many large files

I have about 70 CSV files, all 1GB or so in size. On a windows environment I need to grep through them all to find specific lines.
My search file called "input.txt" contains these strings:
CG234242424
CG234234234
CG234234235
In a Linux environment I would do this:
for line in `cat input.txt`; do grep $line *.csv >> output.txt; done;
How would I do this in Powershell?
Background - I'm a Linux guy, This is a once off request by the business users for an audit.
I'd build a regular expression from the strings in the input file, and then use Select-String to check the CSV files for the presence of that pattern:
$re = (Get-Content 'input.txt' | ForEach-Object { [regex]::Escape($_) }) -join '|'
Select-String -Path '*.csv' -Pattern $re -CaseSensitive > 'output.txt'
But since PowerShell produces structured data rather than simple string output, you may want to make use of that structure:
$re = (Get-Content 'input.txt' | ForEach-Object { [regex]::Escape($_) }) -join '|'
Select-String -Path '*.csv' -Pattern $re -CaseSensitive |
Select-Object Filename, LineNumber, Line |
Export-Csv 'output.csv' -NoType
If you must process each string from the input file separately you'd do it like this:
foreach ($line in Get-Content 'input.txt') {
Select-String -Path '*.csv' -Pattern $line -SimpleMatch -CaseSensitive |
Select-Object Filename, LineNumber, Line |
Export-Csv 'output.csv' -NoType -Append
}

Replace method used along-side Select-String not working

I am trying to search for the string, replace it and then output the file. I believe I have the syntax correct but for whatever reason it is not working. Can anyone spot why or is this even possible?
$DesiredTimeoutTime = '<Settings maxTimeout="04:00:00" />'
$path = "C:\Windows\Settings.log"
$currentTimeoutTime = Select-String -Path $path -SimpleMatch '<Settings maxTimeout=' -CaseSensitive
Write-Host $currentTimeoutTime
(Get-Content $path).Replace((Select-String -Path $path -SimpleMatch '<Settings maxTimeout="'), $DesiredTimeoutTime) | out-file $path
It finds the line and path but it is not saving the changes.
Thank you
You're overcomplicating things. Simply use the -replace operator with an appropriate regular expression:
$DesiredTimeoutTime = '04:00:00'
(Get-Content $path) -replace '(?<=<Settings maxTimeout=")[^"]*', $DesiredTimeoutTime |
Set-Content $path
(?<=...) is a positive lookbehind assertion, which basically means "look for something that is preceded by this pattern".

Powershell -how to remove line details from selectstring output

I want to select a string "install status" from a log file by using powershell. For that i have used the command $status=selectstring -path $path -pattern "installstatus" .This cmd given an output installstatus=success with path and logtime and line details at beginning and i removed the path by adding |{$_.Line} after pattern in $status.And i want to remove line details also.how can i remove those details.I only want the pattern to be displayed .Any help will be apperciated.Thanks in advancd.
here the scenarios
$path="C:\Users\sumith\filename.log";
$status=select-string -path $path -pattern "Install_status"
output is
C:\Users\sumith\filename.log:79:ISS_LOG [14:45:41]: INSTALL_STATUS:SUCCESS
if i give
$status=select-string -path $path -pattern "Install_status" | {$_.Line}
the output will be
ISS_LOG [14:45:41]: INSTALL_STATUS:SUCCESS
now i want to remove ISS_LOG [14:45:41]: from output
IMO you are better of using a regular expression for this:
$File = ".\filename.log"
$Content = (Get-Content $File -raw)
$Pattern = [regex]'INSTALL_STATUS:\s*(\w+)'
"Using -Match operator"
if ($Content -Match $Pattern){
$Matches[0]
$Matches[1]
} Else {
"couldn#T find a match"
}
"Using [RegEx] .Matches method"
$Matches = $Pattern.Matches($Content)
$Matches.Captures[0].Value
$Matches.Captures.Groups[1].Value
Your question and comment differ in the file content,
a space following the colon INSTALL_STATUS: SUCCESS.
Sample output :
Using -Match operator
INSTALL_STATUS: SUCCESS
SUCCESS
Using [RegEx] .Matches method
INSTALL_STATUS: SUCCESS
SUCCESS
Try this,
$status=select-string -path $path -pattern "Install_status" | {$_.Line}
$status.Substring(19)OR
$status=select-string -path $path -pattern "Install_status" | {$_.Line}
$status.Substring($status.IndexOf('IN'))
or
$status=select-string -path $path -pattern "Install_status" | {$_.Line}
$status.Substring($status.IndexOf(']:')+2)
Or using Regex (Credits to LotPengs)
$Content=Get-Content D:\creditdetails.txt
$Pattern = [regex]'INSTALL_STATUS:\s*(\w+)'
if( $Pattern.Matches($Content) -ne $null){
$Matches=$Pattern.Matches($Content)
$Matches.Captures[0].Value
}else{
$Matches='No Match Found'
}
Assuming the log structure remains the same.
For console output (modified Chetan Kulkarni answer)
(Select-String -Path .\file.txt -Pattern 'abcde').line