Replace file content using PowerShell : Single and Multiple files.
Want to replace certain string using powershell?Can be a single file or multiple files on you system..
Powershell offers a very simple way to achieve this and would considerably save your time for better things...
I would start of with editing single file first followed my multiple files..so open PowerShell console as Administrator and type along...
- Editing single file:
Open Notepad and fill it with some random text.. or just copy paste this below text..
Server
Powershell
windows
Hosts
Active Directory
Exchange
Automation
Scripts
DSC
Hosting
Deployment
Administrator
save this as test.txt on your desktop, just ensure you are saving it correctly and not as test.txt.txt which may be appended while saving if not checked.
run the following cmdlet to verify.
change working directory to Desktop or where the test.txt was saved.
Get-Content .\test.txt
now we replace the "hosts" to "virtualhosts" by the below cmdlet.
(Get-Content -Path .\test.txt).Replace("Hosts","VirtualHosts") | Set-Content -Path .\test.txt
and check the content of the file now with the below cmdlet.
Get-Content .\test.txt
- Editing Multiple files:
Now on the desktop., copy/ paste the test.txt file multiple times, may be 5 times.
So, we have five files .txt files which have data in it and we have to replace a specific string in all the five files at the same time.
All we need to do is improvise the above cmdlets into a script.
First we need a cmdlet to list all the txt files in desktop folder.
get-item c:\users\User1\Desktop\*.txt # this would output all the txt files and this has to be stored in a variable for script usage.
$InputFiles = get-item c:\users\User1\Desktop\*.txt # this would store all the file names with .txt extension.
Now we need a for loop, that would enable us to work with each file in the $InputFiles
$InputFiles = Get-Item "C:\Users\User1\Desktop\*.txt" # gathers the files ending with .txt
$OldString = 'Powershell' # string to be replaced with.
$NewString = 'PowerShellisCool' # new string
$InputFiles | ForEach {
(Get-Content -Path $_.FullName).Replace($OldString,$NewString) | Set-Content -Path $_.FullName
} # looping each file with its Fullname until all .txt files are covered and replaced with the new string.
Copy the above code to ps.ps1 and run it in powershell as administrator.
Listing of files in Desktop and showing the content in test.txt
Ran the script ps.ps1 and checking the content in test.txt and other files.
Happy Scripting....
No comments:
Post a Comment