How To Find A String in a File With PowerShell
Introduction
So you have a need to have PowerShell to look for a string in a file and create and entry if it doesn’t find it and do nothing if it does. For my example I am installing an application and I need to add three lines of content, but if it exists I do not want duplicate entries created.
The Code
There are probably other ways to achieve the goal, but my idea was to use Get-Content and read the file and search for my string. The goal is to use variables where we can, to make the code easily re-usable, find our string and if not found add a few lines.
We will create two variables, one called $FileName for the file to search and one called $wordToFind and define them.
$FileName = "C:\uc4g5\SMgr\bin\UCYBSMgr.ini" $wordToFind = "[Destination UC4Q9GAI]"
Now we are ready to use If statement to with Get-Content to search for our string. If found just write out nothing needed to be done and leave, but if not found add a few lines to the file.
If((Get-Content $FileName).Contains($wordToFind)) { Write-Host "No edits needed" } Else { Add-Content -Path $FileName -Value "" -Encoding ASCII Add-Content -Path $FileName -Value "[Destination UC4Q9GAI]" -Encoding ASCII Add-Content -Path $FileName -Value "deffile=*OWN\UC4Q9GAI.smd" -Encoding ASCII Add-Content -Path $FileName -Value "cmdfile=*OWN\UC4Q9GAI.smc" -Encoding ASCII }
Not much to it. Script does exactly as planned and is re-usable due to the variables.
Conclusion
By using the Get-Content cmdlet with If statement we were able to look for a string in a file and add or do nothing.
Leave a Reply