PowerShell: Replace 1 Line in a Text File Matching Certain Values

# replaceLine -textContent $fileContent -match $url -updateLineContent $record
function replaceLine($textContent,$match,$updateLineContent){
    $line = $textContent | Select-String $match | Select-Object -ExpandProperty Line
    return $textContent -replace $line,$updateLineContent
}
# Usage
$content=get-content c:\windows\system32\drivers\etc\hosts
$updatedContent=replaceLine $content 'x.acme.com' '#1.1.1.1 kimconnect.com'

#Save this new content if it is 100% correct, be mindful with this cmdlet
#$updatedContent|set-content

# Output:
# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#1.1.1.1 kimconnect.com

# localhost name resolution is handled within DNS itself.
#       127.0.0.1       localhost
#       ::1             localhost

Leave a Reply

Your email address will not be published. Required fields are marked *