I want to pull out a string from a txt file that shows how fast my SQL Server backups run. This shows me the line that contains the information:
Select-String -Path "DatabaseBackup - USER_DATABASES - FULL*.txt" -pattern "MB/sec"
The problem is that the line of text is over 2000 characters so I want to pipe it to substring to grab just a portion. Unfortunately, this code:
Select-String -Path "DatabaseBackup - USER_DATABASES - FULL*.txt" -pattern "MB/sec" | ForEach-Object { $_.substring(42,30) }
gives
Method invocation failed because [Microsoft.PowerShell.Commands.MatchInfo] does not contain a method named 'substring'.
Any hints on how to get this working?
Ken
[Edit] The solution is provided by JosefZ. For my own future reference, the database names are enclosed with single quotes and the speed is enclosed in open and close round brackets. This code:
Select-String -Path "DatabaseBackup - USER_DATABASES - FULL*.txt" -pattern "MB/sec" |
ForEach-Object {
$_.Line.substring($_.Line.IndexOf(''''), $_.Line.IndexOf('''', $_.Line.IndexOf('''') 1)-$_.Line.IndexOf('''') 1) " " $_.Line.substring($_.Line.IndexOf('('),$_.Line.IndexOf(')')-$_.Line.IndexOf('(') 1)
}
produces output that looks like:
'DBA' (796.230 MB/sec)
'ReportServer' (488.596 MB/sec)
'ReportServerTempDB' (139.270 MB/sec)
'TSTGP' (420.375 MB/sec)
CodePudding user response:
Select-String: By default, the output is a set of MatchInfo
objects with one for each match found.
Apply .substring
method to the $_.Line
string, e.g. as follows:
Select-String -Path "DatabaseBackup - USER_DATABASES - FULL*.txt" -pattern "MB/sec" |
ForEach-Object { $_.Line.substring(42,30) }
CodePudding user response:
Select-String
is returning a MatchInfo
object so you would need to iterate over the Matches
property of that object.
So you could do something like this:
(Select-String -Path "DatabaseBackup - USER_DATABASES - FULL*.txt" -pattern "MB/sec").Matches |
ForEach-Object { $_.substring(42,30) }