Specifying Bit Flags Smart

by May 21, 2019

In the previous tip you have seen how you can enable all SSL security protocols in PowerShell to connect to web services and web sites:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Ssl3 -bor [Net.SecurityProtocolType]::Tls -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12

Funny enough, a much shorter line will work just as well:

[Net.ServicePointManager]::SecurityProtocol = 'Ssl3, Tls, Tls11, Tls12'

Here is why:

Since the SecurityProtocol property is of Net.SecurityProtocolType type, when you submit string data instead, it is auto-converted:

 
PS> [Net.ServicePointManager]::SecurityProtocol.GetType().FullName 
System.Net.SecurityProtocolType 
 

Rather than using the SecurityProtocolType enumeration and concatenate flags with the -bor operator, you can use a comma-separated string with the bitflag names. These two are equivalent:

$a = [Net.SecurityProtocolType]::Ssl3 -bor [Net.SecurityProtocolType]::Tls -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12
$b = [Net.SecurityProtocolType]'Ssl3, Tls, Tls11, Tls12'
 
PS> $a -eq $b
True 
 

psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want to miss: PowerShell Conference EU – with 40 renown international speakers including PowerShell team members and MVPs, plus 350 professional and creative PowerShell scripters. Registration is open at www.psconf.eu, and the full 3-track 4-days agenda becomes available soon. Once a year it’s just a smart move to come together, update know-how, learn about security and mitigations, and bring home fresh ideas and authoritative guidance. We’d sure love to see and hear from you!

Twitter This Tip! ReTweet this Tip!