Using PowerShell to replace text in a file.
I have a custom class next week. I need to make a little fix to the lab files… actually 526 .css files and 380 .htm files need to be updated with several fixes in each. Lots of little fixes.
How did I know how many files? PowerShell of course…
(Get-ChildItem *.css –Recurse).count
Find and replace some text…
First update was to fix some URLs. I needed to remove a backslash at the start of every "href=" and "src=". A little PowerShell could also do all of the file edits!
$from = 'href="/'
$to = 'href="'
Get-ChildItem *.htm -recurse |
%{
$name = $_.fullname; Write-Host $name; (Get-Content $name) |
%{ $_ -replace $from,$to } |
Set-Content -path $name –force
}
I wrapped the above line in a function, called it eight times with my eight replacements, and it was done in seconds!
Notes:
Find all of the files…
Get-ChildItem *.htm -recurse
and run some code on each one:
%{ }
Save the file path to a variable, display the file path and then get the file's contents:
$name = $_.fullname;
Write-Host $name;
(Get-Content $name)
The pipe then has the text to be replaced, so let's do the replace:
%{ $_ -replace $from, $to }
And write the replaced text out to a file with the same name:
Set-Content -path $name –force
.
2 comments:
Hi Mike, I have configured Remote SharePoint and want to increase the idletimeout period. Can you give me some direction on that?
What is "Remote SharePoint"? Remote access to a SP server from PowerShell? Remote SP server for TFS? Remote Desktop?
Post a Comment
Note to spammers...
Spammers, don't waste your time... all posts are moderated. If your comment includes unrelated links, is advertising, or just pure spam, it will never be seen.