A question came up on the PowerShell newsgroup concerning how to use enums, particularly the shortcut form whereby posh will coerce strings. Roman Kuzmin of PowerShell/FarNet fame offered up a quick answer on how to provide multiple values to be "or'd" together for [flags] decorated enums:
$srv.ReplicationServer.Script("Creation,SomeOtherValue")
To which the original poster (moff) replied:
Out of interest, can this syntax be used for xor'ing values together too? At the moment my statement looks like this: $pub_svr.ReplicationServer.Script(([Microsoft.SqlServer.Replication.scriptoptions]::Creation ` -bor [Microsoft.SqlServer.Replication.scriptoptions]::IncludeAll ` -bxor [Microsoft.SqlServer.Replication.scriptoptions]::IncludeReplicationJobs ))
To which I explained that sure, one way has you casting the operands (using system.attributetargets as the enum example):
$targets = ([attributetargets]"all" -bxor [attributetargets]"event,field")
And if the type name is long, another handy trick is to assign the enum type to a variable, e.g.
$enum = [Microsoft.SqlServer.Replication.ScriptOptions] $options = ($enum::creation -bor $enum::IncludeAll) -bxor $enum::includereplicationjobs
...and finally, if you want to cast multiple flags using a variable shortcut, use the -as operator:
$options = $enum::all -bxor ("includeall,includereplicationjobs" -as $enum)
because [$enum]"creation,includeall" (or other guessed-at variants) won't work.
Page rendered at Friday, September 05, 2008 9:38:16 PM (Eastern Standard Time, UTC-05:00)
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.