I was surprised the other day when I was testing out a post-install PowerShell script that modified the contents of an XML file. I’ve become so familiar with PowerShell 3.0/4.0 improvements, that I forgot some of the ways 2.0 handled arrays when it came to methods.
I originally was testing my script against Windows 2012 servers, on PowerShell 3.0. Here is a simple breakdown of what it was doing:
Awesome. I modified the value for Thread.
When I went to test this in PowerShell 2.0, I ran into the problem of running methods against arrays of objects. This changed in version 3.0. This is the error you get in 2.0, since the method is expecting a single object:
Notice how I first checked with Get-Member (GM is a built-in alias), and found that there is a Replace method available? It makes it look like it would work the same way – thus my confusion. Higher versions will be able to notice whether there are multiple objects that the method should run against, rather than error out. I just used the -replace operator as the solution, which will work on all of the PowerShell versions we use in our environment:
Issue taken care of 🙂
- This post on StackOverflow goes into special differences of operators vs. methods, and why you may experience different results
- To learn more about operators, take a look at about_operators and about_Comparison_Operators
- Want to take a peek at extra features/improvements being introduced in the next version of PowerShell? Check out the Windows Management Framework 5.0 Preview
- If you are on PowerShell 3.0 or 4.0, you can launch a PowerShell 2.0 session to test out commands: