我有一个奇怪的问题。我有一个函数应该返回1或2个值,一个字母和一个数字。 出于某种原因,它仅在我将返回指定为
时才有效return $x, $y
但它不会像这样工作:
return $x
return $y
代码:
$ModelsDesktop = @("Dimension","Optiplex")
$ModelsLaptop = @("Latitude","Venue")
<#
Returns L or D depending on the Computer Name. Sets U if the model is uncertain.
#>
Function Get-TypeByComputerName{
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
[ValidateNotNullOrEmpty()]
[string]$ComputerName
)
Process {
if ($ComputerName -like "*-L-*" -or $ComputerName -like "*-LT-*") {
$ModelType = "L"
}
elseif ($ComputerName -like "*-D-*" -or $ComputerName -like "*-WRK-*") {
$ModelType = "D"
}
else {
$ModelType = "U" #unsure
}
return $ModelType
}
}
<#
Returns L or D depending on the Computer Model. Sets U if the model is uncertain.
#>
Function Get-TypeByModel{
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
[ValidateNotNullOrEmpty()]
[string]$Model
)
Process {
if (($ModelsLaptop | %{($Model) -like("*$_*")}) -contains $true) {
$ModelType = "L"
}
elseif (($ModelsDesktop | %{($Model) -like("*$_*")}) -contains $true) {
$ModelType = "D"
}
else {
$ModelType = "U"
}
return $ModelType
}
}
<#
Returns L or D depending on the Computer Name and Model. Sets a flag if the model is uncertain.
#>
Function Get-Type{
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$ComputerName,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$Model
)
Process {
if ((($ComputerName | Get-TypeByComputerName) -eq ($Model | Get-TypeByModel)) -and (($ComputerName | Get-TypeByComputerName) -ne "U")) {
$ModelType = ($ComputerName | Get-TypeByComputerName)
}
elseif (($ComputerName | Get-TypeByComputerName) -ne "U") {
$ModelType = ($ComputerName | Get-TypeByComputerName)
$Flag = 1
}
elseif (($Model | Get-TypeByModel) -ne "U") {
$ModelType = ($Model | Get-TypeByModel)
$Flag = 1
}
else {
$ModelType = "D"
$Flag = 1
}
return $ModelType
return $Flag
}
}
价值:
$test = New-Object psobject -Property @{ComputerName="crd-l-02-00001";Model="opti 343"}
输出2个返回语句(如前面的代码所示):
$test
ComputerName Model
------------ -----
crd-l-02-00001 opti 343
PS C:\Users\u0096902> (Get-Type -ComputerName $test.ComputerName -Model $test.Model)
L
输出更正后的&#34;返回$ ModelType,$ Flag&#34;:
$test
ComputerName Model
------------ -----
crd-l-02-00001 opti 343
PS C:\Users\u0096902> (Get-Type -ComputerName $test.ComputerName -Model $test.Model)
L
1
我错过了什么?似乎无法解决这个问题。它似乎只返回第一个&#34; return&#34;,但我不知道为什么。
此示例代码似乎完全正常:
function get-multiplereturnvalues {
"Return value 1"
"Return value 2"
}
$return = get-multiplereturnvalues
$return[0] # Outputs "Return value 1"
$return[1] # Outputs "Return value 2"
答案 0 :(得分:3)
&#34;在计算机编程中,return语句导致执行离开当前子例程,并在调用子例程之后立即恢复到代码中的点,称为其返回地址。&#34;
一旦你致电回复,你就说你已经完成了这项功能。
答案 1 :(得分:3)
来自Get-Help about_Return
:
详细说明 Return关键字退出函数,脚本或脚本块。有可能 用于退出特定点的范围,返回值或指示 已达到范围的结束。
你的第一个Return
强制立即退出该功能,所以第二个永远不会有机会运行。