Please explain what "% i*g" means in this PowerShell script

Viewed 144

While working in PowerShell I needed to convert CIDR notation to IP starting address and subnet mask notation.

Performing a Google search I found this Reddit posting challenge that contained many obscure ways to perform this task.

One that I found particularly interesting was:

$C = 13
[ipaddress](4.GB-(4GB-shr$C))|% i*g 

It took me a while to see that -shr$C was merely the PowerShell -shr operator without any white space before the $C variable reference.

I then needed to search to find that % is an alias for Foreach-Object.

By just querying the value of [ipaddress](4.GB-(4GB-shr$C)) I received:

Address            : 63743
AddressFamily      : InterNetwork
ScopeId            :
IsIPv6Multicast    : False
IsIPv6LinkLocal    : False
IsIPv6SiteLocal    : False
IsIPv6Teredo       : False
IsIPv4MappedToIPv6 : False
IPAddressToString  : 255.248.0.0

Which showed me the properties of the IPAddress object. The result that I need is the IPAddressToString property which I could get by using %| IPAddressToString or somehow coerce PowerShell to emit the object as a string.

Therefore, the question now is what does the syntax % i*g mean?

What is i and g and are we performing multiplication?

1 Answers

For more examples, I'm going to refer you to my post in Programming Puzzles.

% is an alias for ForEach-Object which has a parameter set that accepts a property name.

You've already seen this in your use of %| IPAddressToString.

The parameter accepts wildcards though, so |% i*g means to invoke the member whose name matches that pattern, which in this case is i paddresstostrin g.

The pattern must resolve unambiguously, so try doing |% i* and you'll see an error which helpfully tells you all the members that pattern could match.

The reason this is not multiplication is that it's a string. Since it's a parameter to a command, the string doesn't necessarily need to be quoted.

Related