How to extract a certain part of a string in powershell

Viewed 11803

I want to extract the last 4 digits before ".txt" from this string:

09/14/2017 12:00:27 - mtbill_post_201709141058.txt 7577_Delivered: OK

Those represent the time at which that log was created and I want to display it as 10:58. I read from a file that has multiple lines similar to the one displayed.

Get-Content file.txt | ForEach-Object {
$splitUp = $_ -split "_"
$SC=$splitUp[2] -split "_"
Write-Host $SC
$len = $SC.Length
$folder2 = $SC.Substring($len - 12, 42)
}

I tried separating the string by "_" and then counting the characters in the obtained string and tried separating by the "Substring" command, but I receive the following error.

Exception calling "Substring" with "2" argument(s): "StartIndex cannot be less than zero. Parameter name: startIndex"

At line:6 char:5 + $folder2 = $SC.Substring($len - 12, 42)

  • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    • CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    • FullyQualifiedErrorId : ArgumentOutOfRangeException
3 Answers
Related