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

Basic CSS: Use Abbreviated Hex Code

<style> .red-text { color: #000000; } .fuchsia-text { color: #000000; } .cyan-text { color: #000000;…

Linux: How To Install Visual Studio Code

Intro Bypassing any discussions about choosing Visual Studio Code (VS Code) over Atom or Sublime…

PowerShell: Increase CPU Count or Memory of VMs via Virtual Machine Manager

# IncreaseCpuandRamViaVMM.ps1 # User Input Variables $vmNames=@( 'TESTWINDOWS', 'TESTWINDOWS2' ) $vmmServer=$env:computername $setCpuCount=8 $setDynamicMemory=$false $dynamicMemoryMinimumGB='2GB' $dynamicMemoryMaximumGB='16GB'…
Other project: DragonCoin.com