Reputation: 1173
I have 2 pieces of code:
# code 1:
[type]$t1 = [switch]
# all is ok, code works as expected
#code 2:
function test ([type]$t2) { }
test -t2 [switch]
# here we get error. can't convert from string to system.type
I know, I can write: test -t2 "System.Management.Automation.SwitchParameter"
, but it's ugly!!
Why can i set [switch] to [type]variable, but can't pass it to function??
Upvotes: 2
Views: 5185
Reputation: 26749
Wrap the argument to the test function as an expression and it will return the type:
function test ([type]$t2) { }
test -t2 ([switch])
Upvotes: 2
Reputation: 126732
PowerShell lets you can create types with a cast:
PS> [type]"switch"
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False SwitchParameter System.ValueType
What you're actually doing is passing the type name enclosed in brackets:
PS> [type]"[switch]"
Cannot convert the "[switch]" value of type "System.String" to type "System.Type".
So you need to pass just the name of the type:
test -t2 switch
or
test -t2 ([switch].fullname)
Upvotes: 4
Reputation: 301147
You can do this:
test -t2 "switch"
Or you can use the example from code1 and pass in the $t1
itself:
function test ([type]$t2) { }
[type]$t1 = [switch]
test -t2 $t1
Upvotes: 3