gpt4 book ai didi

powershell v2 函数,如何在不命名第二个参数的情况下为第一个参数设置默认值?

转载 作者:行者123 更新时间:2023-12-03 01:12:51 25 4
gpt4 key购买 nike

问题很简单。我有一个带有两个参数的函数,我希望能够在它具有默认值 时调用它而不提供第一个参数。没有命名第二个 .
例如(这不是我真正的功能,而是一个简单的例子来说明我的意思)

function foo 
{ param([int]$int=-1,[string]$str="''")
$int
$str
}

我希望强制参数列表中的类型将使 PS 将正确的值绑定(bind)到正确的参数,但事实并非如此
PS C:\> foo
-1
''
PS C:\> foo 1
1
''
PS C:\> foo 1 x
1
x
PS C:\> foo -str x
-1
x
PS C:\> foo x
foo : Impossible de traiter la transformation d'argument sur le paramètre «int». Impossible de convertir la valeur «x» en type «System.Int32». Erreur: «Le format de la chaîne
d'entrée est incorrect.»
Au caractère Ligne:1 : 5
+ foo x
+ ~
+ CategoryInfo : InvalidData : (:) [foo], ParameterBindingArgumentTransformationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,foo

在 PS 中我想要什么?

编辑

这是我正在尝试做的一个更好的例子

测试.ps1
[cmdletbinding()]
param(
[parameter()]
[string[]]$___where=@('*')
)

function InvokeOn {
[cmdletbinding()]
param(
[string[]]
${___names}=@('*'),

[scriptblock]
${___block}
)
$___doExec = ($___names -contains '*')
foreach($___name in $___names) { $___doExec = ($___doExec -or ($___where -contains $___name)) }
if($___doExec) { &$___block }
}

$null = new-item alias:__LOG__ -value InvokeOn

__LOG__ c1 { Write-host '-- 1 --' }
__LOG__ c2 { Write-host '-- 2 --' }

__LOG__ c1,c2 { Write-host '-- 1 or 2 --' }

__LOG__ { Write-host 'always, defaulted' }
__LOG__ -___block { Write-host 'always, named' }

还有一些跑
PS C:\> .\test
always, named
PS C:\> .\test c1
-- 1 --
-- 1 or 2 --
always, named
PS C:\> .\test c2
-- 2 --
-- 1 or 2 --
always, named
PS C:\> .\test c2,c1
-- 1 --
-- 2 --
-- 1 or 2 --
always, named

如您所见, __LOG__ { Write-host 'always, defaulted' }永远不会触发,因为 PS 将脚本 block 绑定(bind)了错误的参数。

参数名称是故意复杂的,开发人员甚至不应该使用别名函数知道。

交换参数是不切实际的,因为脚本 block 可能很长,即使是短的,请假设 __LOG__会激发更少的可读性。

解决方案

应用 majkinetor 的想法,我以这种方式修改了我的代码
function InvokeOn {
[cmdletbinding()]
param(
[string[]]
${___names} = @('*'),

[scriptblock]
${___block}
)
if(!$PSBoundParameters.ContainsKey('___block')) { $___names,$___block = @('*'),[scriptblock]::create($___names[0]) }
$___doExec = ($___names -contains '*')
foreach($___name in $___names) { $___doExec = ($___doExec -or ($___where -contains $___name)) }
if($___doExec) { &$___block }
}

现在它按预期工作:)

最佳答案

您可以执行以下操作:

 function foo 
{
param ($int=-1,[string]$str="''")
if ($int.gettype().Name -eq 'String') { $str = $int; $int = -1 }
$int
$str
}

通知 - $int不能有类型。

关于powershell v2 函数,如何在不命名第二个参数的情况下为第一个参数设置默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36379792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com