Remove line from text file

Welcome Forums General PowerShell Q&A Remove line from text file

This topic contains 2 replies, has 2 voices, and was last updated by

 
Participant
5 years, 3 months ago.

  • Author
    Posts
  • #8392

    Participant
    Points: 0
    Rank: Member

    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

    Member
    Points: 0
    Rank: Member
    $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

    Participant
    Points: 0
    Rank: Member
    $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

    Thank you.

The topic ‘Remove line from text file’ is closed to new replies.