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: Function to Confirm Certain Contents

It's always a good idea to receive user confirmations prior on proceeding to making important…

Upgrade Virtual Hardware Version in VMM

The following script will upgrade all guest virtual machines from a lower version to the…

PowerShell: Microsoft Dynamics Update All Organizations

# updateCrmOrgs.ps1 function updateCrmOrgs{ try{ Add-PSSnapin Microsoft.Crm.Powershell $servers=Get-CrmServer $highestVersion=($servers.Version|measure-object -Maximum).Maximum $lowVersionServers=$servers|?{[version]$_.Version -lt [version]$highestVersion} if($lowVersionServers){ write-warning…