Remove line from text file

Home Forums PowerShell Q&A Remove line from text file

You must be registered and logged in to reply to this topic.

This topic contains 2 replies, has 2 voices, and was last updated by  Lery 1 year ago.

  • #8392

    Lery
    Participant

    I have a text file located at c:\computers.txt.  Inside this file is the following:

    computer1

    computer 345

    computername

    computer 7 8 8

    I want to delete a line from this file.  The trick is, to delete only what I enter into a variable.  So if $deletecomputer = 'computer 345' I want to delete just computer 345.  The variable would could contain any one computername.

    Everything I've found shows how to replace text.  I'm not necessarily looking to replace.  I'm looking to delete.

  • #8394

    Art Beane
    Participant
    $Computers = Get-Content C:\computers.txt
    $del = Read-Host -Prompt "Enter Computer name to delete"
    $Computers = $Computers | Where {$_ -ne $del}
    $Computers | Out-File C:\computers.txt -Force
    #8403

    Lery
    Participant
    $Computers = Get-Content C:\computers.txt
    $del = Read-Host -Prompt “Enter Computer name to delete”
    $Computers = $Computers | Where {$_ -ne $del}
    $Computers | Out-File C:\computers.txt -Force[/pre]
    

    Thank you.

You must be registered and logged in to reply to this topic.