Search This Blog

Sunday, February 06, 2011

Powershell– Comma Operator and Percentage (%) Alias

Ok, I have been dabbling more into the world of PowerShell, and wanted to note a couple of things I have come across.

% (Percentage) Alias

I have seen % used before bracketed statements.

% ($banana), basically the percentage is short hand for ForEach-Object ()

Get-Content ServerList.txt | ForEach-Object{,($_.split(','))


Get-Content ServerList.txt | %{,($_.split(','))

The line above gets the contents of the file serverlist.tzt and pipes it. Then ForEach-Object loops through each object passed (in this case it will be each line read from the file.

Comma Operator

In doing the above command splitting the array and piping it, I had issues displaying the array elements. I came across this post which helps explain what's going.

But the author used ,() to get round the issue and I wondered what this was doing.

,($_.Split(" "))

In the end I think all the ,() is doing is putting the object into a single element array which stops PowerShell flattening out the array. I base my understanding on this page from MS.


No comments:

Post a Comment