2

I have a text file full of TV shows with an ID at the end of their name in each line of a text document. I want to ignore any blank line or ignore any errors

Get-Content -Path "C:\test\text.txt" | ForEach-Object  {
    $_.Substring($_.Length - 5) -ErrorAction 'SilentlyContinue'
}

I tried to suppress any errors like this but that didn't resolve the issue. How can I skip blank lines or suppress the error messages in a foreach loop?

1
  • The parameter -ErrorAction can be used with cmdlets, but not with object methods. Commented May 23, 2017 at 11:55

1 Answer 1

5

You can change the error action variable globally before your code, and then set it back to it's previous value afterwards:

$PrevErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = 'silentlycontinue'

Get-Content -Path  "C:\test\text.txt" | ForEach-Object  {
    $_.Substring($_.Length - 5)
}

$ErrorActionPreference = $PrevErrorActionPreference

Alternatively, just use an If statement to test for the Length of the string before using SubString:

Get-Content -Path "*.txt" | ForEach-Object  {
    If ($_.Length -ge 5) { $_.Substring($_.Length - 5) }
}

A third option would be to use a Try..Catch block:

Get-Content -Path "*.txt" | ForEach-Object  {
    Try {
        $_.Substring($_.Length - 5)
    } Catch {
        # Do nothing
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.