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

How To Modify a Windows Service

Here's the freebie code: # Version 0.02 $serviceName='Windows_Exporter' $newExePath=$false $newSwitches=" --log.format logger:eventlog?name=$serviceName --collectors.enabled os,cpu,cs,logical_disk,net,tcp,service,textfile" function…

PowerShell: Create and Edit SMB Shares

# Create SMB Share $sharePath='C:\testshare' $accessList="$env:USERDOMAIN\Domain Admins","NT AUTHORITY\Authenticated Users" $shareName=split-path $sharePath -leaf mkdir $sharePath New-SmbShare…

Bash Shell: Old School Migration of ESXi Guest Virtual Machines

Step 0: Preparations Estimate file-copying duration for cut-over:- Sustained storage transfer speed using a 1GB…
Other project: DragonCoin.com