I’ve only recently discovered the “multiple assignment” feature in PowerShell via the Windows PowerShell blog. I’m not sure what I was searching for when I stumbled upon it but my first thought when I saw it was “I bet this will make modifying arrays easy!” As some of you may be aware, modifying arrays of object type “string” are a pain in the butt in PowerShell and unless you create the variable as a Collections “ArrayList” object you’re going to be struggling. But, the beforementioned feature makes it so much easier!
For example, I needed to remove 1 line from an INI file on a PC and the potential for doing this to many PC’s prompted me to write a script. I could do the following:
$originalFile = get-content path-to-INI-file
This gets the entire contents of the file. Get-Content is a widely used cmdlet and it stores the content into a string-type array. That’s not such a pain anymore to work with when I want to remove an element from it. First I would search for whatever I want to remove and find it’s index:
$removeIndex = $originalFile.IndexOf($originalFile -match “LogLevel=Finest”)
$newFile = $originalFile[0 .. ($removeIndex – 1)],$originalFile[($removeIndex + 1) .. $originalFile.count]
Set-Content path-to-INI-file $newFile
I could have easily overwritten $originalFile instead of creating $newFile. The gotcha above is that your search term has to be unique. If the match returns multiple results the “indexOf” method will break. You can add the index to the end of the match by adding [] if you know which match it will be ( $orginalFile.IndexOf(($originalFile -match “LogLevel=Finest”)[0]) will return the first match).
This made my life so much easier when I had to write this script to modify multiple configuration files to flip systems to a test mode.
You must be logged in to post a comment.