locked
Read Content From File RRS feed

  • Question

  • I have a txt File named changeletter.txt with the following line on it

    C:\Program Files\

    I'm trying to read the content of the file to check for the existence C:\ in the following statement:

    If ((Get-Content -Path "C:\changeletter.txt").Contains("C:\") -eq $true){

       Do something here

    }

    However, it seems to be ignoring the existence of C:\ on the file because it's written as C:\Program Files\

    If I remove C:\Program Files\ from the text file and only have C:\ then the value returns true and enters the If Statement.

    What I'm I missing?

    Wednesday, December 28, 2016 5:42 PM

Answers

  • So I tried your suggestion but I also had some issues with it.  It wouldn't work if there were multiple lines on the text file.  However, I found another way using Select-String.

    Get-Content C:\changeletter.txt | Select-String 'C:\\' -quiet

    It looks for C:\ and if it finds it, it returns true if you use the -quiet operator

    Thanks for the help!

    • Marked as answer by Diango Thursday, December 29, 2016 10:43 PM
    Thursday, December 29, 2016 10:43 PM

All replies

  • "Contains" checks for the existence of an item in an array. The -match operator fits much better for your purpose.
    'C:\Program Files\' -match 'C:\\'
    Because of the "\" is a special charachter in regular expressions you have to escape it in the search pattern.

    Grüße - Best regards

    PS:> (79,108,97,102|%{[char]$_})-join''

    • Proposed as answer by Hello_2018 Thursday, December 29, 2016 4:47 AM
    • Unproposed as answer by Diango Thursday, December 29, 2016 10:43 PM
    Wednesday, December 28, 2016 5:55 PM
  • So I tried your suggestion but I also had some issues with it.  It wouldn't work if there were multiple lines on the text file.  However, I found another way using Select-String.

    Get-Content C:\changeletter.txt | Select-String 'C:\\' -quiet

    It looks for C:\ and if it finds it, it returns true if you use the -quiet operator

    Thanks for the help!

    • Marked as answer by Diango Thursday, December 29, 2016 10:43 PM
    Thursday, December 29, 2016 10:43 PM
  • I have a txt File named changeletter.txt with the following line on it


    So I tried your suggestion but I also had some issues with it.  It wouldn't work if there were multiple lines on the text file.

    You did not mention that there would be more than one line. If you do not tell us the concrete circumstances we cannot help you in the proper way. Of coure you have to deal with it in a different way when you have different conditions.  :-/

    What do you do when you have more than one match in your file?


    Grüße - Best regards

    PS:> (79,108,97,102|%{[char]$_})-join''


    • Edited by BOfH-666 Friday, December 30, 2016 12:56 AM
    Friday, December 30, 2016 12:37 AM