[英]Get type of variable from parameter using PowerShell
How do I get the type of the variable from a parameter using PowerShell? 如何使用PowerShell从参数中获取变量的类型?
Something to the effect of if TypeOf(xyz) is String or if TypeOf(xyz) is integer . 如果TypeOf(xyz)为String或TypeOf(xyz)为integer的话,会产生一些影响 。
For my purpose I want to check if it is a string or a securestring. 出于我的目的,我想检查它是字符串还是安全字符串。 I would like to use a single function with a parameter. 我想将单个函数与参数一起使用。 Not two separate functions, one for a securestring and one for a string. 不是两个单独的函数,一个用于安全字符串,一个用于字符串。
The direct answer to your question is to use the -is
operator : 您问题的直接答案是使用-is
运算符 :
if ($xyz -is [String]){}
if ($xyz -is [SecureString]){}
if ($xyz -isnot [int]){}
However, digging deeper: 但是,深入研究:
I would like to use a single function with a parameter. 我想将单个函数与参数一起使用。 Not two separate functions, one for a securestring and one for a string. 不是两个单独的函数,一个用于安全字符串,一个用于字符串。
You can use a single function, with parameter sets to distinguish between which version you're using: 您可以使用一个带有参数集的函数来区分所使用的版本:
function Do-Thing {
[CmdletBinding()]
param(
[Parameter(
ParameterSetName = 'Secure',
Mandatory = $true
)]
[SecureString]
$SecureString ,
[Parameter(
ParameterSetName = 'Plain',
Mandatory = $true
)]
[String]
$String
)
switch ($PSCmdlet.ParameterSetName)
{
'Plain' {
# do plain string stuff
}
'Secure' {
# do secure stuff
}
}
}
Go ahead and run that sample definition, and then look at the help: 继续并运行该示例定义,然后查看帮助:
Get-Help Do-Thing
You'll see the generated parameter sets, which show the two ways you can call it. 您将看到生成的参数集,其中显示了两种调用方法。 Each way has a single, mutually-exclusive parameter. 每种方式都有一个相互排斥的参数。
NAME Do-Thing SYNTAX Do-Thing -SecureString <securestring> [<CommonParameters>] Do-Thing -String <string> [<CommonParameters>]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.