Find and Replace Text in Files

There may be occasions where you need to search for something in a text file, and if found, replace it with something else.  I have found this very handy for when we need to globally replace a setting in the BIOS config file for every HP model we support.  I’ll #-explain every step in the script below.

				
					#  Here is where we set a few variables, just to make the scripting easier.
#  $Dev is the location of the BIOS config files.
#  $old is the old setting, $new is the new setting we want to set.

$Dev = '\\myserver\Win10\BIOS\HP'
$Pattern = '^OS Recovery$' # <- Regex matching used here to ensure start and end of line
$old = 'OS Recovery
	Disable
	*Enable'
$new = 'OS Recovery
	*Disable
	Enable'
	
# You could also use regular exrpessions, for example:

$old = 'OS Recovery\r\n\tDisable\r\n\t\*enable'

#  And here is the script.  Get-ChildItem is the cmdlet that looks for files.
#  We are looking for any file in the $Dev path, with the file extension of .bios.
#  Putting .fullname at the end is the same as saying " | select-object -expandproperty fullname".
#  Foreach-object is exactly what it seems like: for every file found, do the following.
#  Get-Content reads out the contents of the file, and the replace function tells it to replace
#  the old string with the new one.  This puts the entire contents of the file into a buffer,
#  and then set-content writes the entire thing back to the original file.  $_ represents the object
#  in the pipeline.

(Get-ChildItem -path $Dev -Recurse *HD_Boot_UEFI.bios | Select-String -Pattern $Pattern).path |
     ForEach-Object {(Get-Content -raw $_).replace($old, $new) | Set-Content $_}
     
# If you used Regular Expressions instead of a literal string, your script needs to use the replace operator
# like this:

(Get-ChildItem -path $Dev -Recurse *HD_Boot_UEFI.bios | Select-String -Pattern $Pattern).path |
     ForEach-Object {Get-Content -raw $_ -replace $old, $new | Set-Content $_}
     
				
			

Leave a Reply

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