如何使用扩展 Powershell 对象的方法 return 参考值?
How to return a reference value with a method from an extended Powershell object?
我正在尝试使用
的方法扩展 Powershell 对象
- returns一个true或false表示成功
- 通过引用输出一个值 (
[ref]
)
我的 模块 MyExtensions.psm1
中有。
Update-TypeData -TypeName [MyType] -MemberType ScriptMethod -memberName TryGetValue -force -value `
{
param(
$myInput,
[ref]$myOutput
)
try
{
# do something with $myInput
$myOutput = …
return $true
}
catch
{
return $false
}
}
目标是能够在脚本或其他模块中编写:
Import-Module MyExtensions
$myInput = …
$value = $null
if($myTypeItem.TryGetValue($myInput, $value)
{
# I know that the $value is good
}
通过引用使用参数(你只是错过了 $myOutput.Value =""
)
function addition ([int]$x, [int]$y, [ref]$R)
{
$Res = $x + $y
$R.value = $Res
}
$O1 = 1
$O2 = 2
$O3 = 0
addition $O1 $O2 ([ref]$O3)
Write-Host "values from addition $o1 and $o2 is $o3"
更完整的答案here。
我正在尝试使用
的方法扩展 Powershell 对象- returns一个true或false表示成功
- 通过引用输出一个值 (
[ref]
)
我的 模块 MyExtensions.psm1
中有。
Update-TypeData -TypeName [MyType] -MemberType ScriptMethod -memberName TryGetValue -force -value `
{
param(
$myInput,
[ref]$myOutput
)
try
{
# do something with $myInput
$myOutput = …
return $true
}
catch
{
return $false
}
}
目标是能够在脚本或其他模块中编写:
Import-Module MyExtensions
$myInput = …
$value = $null
if($myTypeItem.TryGetValue($myInput, $value)
{
# I know that the $value is good
}
通过引用使用参数(你只是错过了 $myOutput.Value =""
)
function addition ([int]$x, [int]$y, [ref]$R)
{
$Res = $x + $y
$R.value = $Res
}
$O1 = 1
$O2 = 2
$O3 = 0
addition $O1 $O2 ([ref]$O3)
Write-Host "values from addition $o1 and $o2 is $o3"
更完整的答案here。