Posted On June 14, 2020

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

kimconnect 0 comments
blog.KimConnect.com >> Codes >> 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 *

Related Post

PowerShell: Accessing the Reflection Assembly Class to Retrieve User Context

Step 1: Accessing Reflection Assembly namespace to call method Load with Windows Account Management as…

A Few Todos while Securing Apache Server

- Install mod_security - Set expose_php = Off in php.ini - Set SecResponseBodyAccess Off in…

PowerShell: Probe Remote Machine for Its OS Type

function probeOsType($server){ $ping=test-connection $server -count 1 $ttl=$ping.ResponseTimeToLive $osType=switch($ttl){ {$_ -le 64} {"Linux"; break} # MacOs…