12 January 2015

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.


There are no comments.



You must be logged in to post a comment.

Links

RSS 2.0 Feed

Support

Brave Rewards
This site supports Brave Rewards. Please consider tipping or adding it to your monthly contributions if you find anything helpful!

For other ways: Support

Support this blog! If you have found it helpfu you can send me crypto. Any amount is appreciated!
ETH: 0xBEaF72807Cb5f4a8CCE23A5E7949041f62e8F8f0 | BTC: 3HTK5VJWr3vnftxbrcWAszLkRTrx9s5KzZ | SHIB: 0xdb209f96dD1BdcC12f03FdDfFAD0602276fb29BE
Brave Users you can send me BAT using the browser.