Powershell将参数值传递给参数并返回

Bio*_*nic 6 powershell

好的.我正在尝试完成一项学校作业,而且不能为我的生活弄清楚这一点.我正在尝试使用powershell将值从一个函数传递到另一个函数,从而形成一个"模块化"类型的脚本.我似乎无法弄清楚如何在不使用$ script:xxxxx的情况下将值移出函数范围.是否有另一种方法可以将powershell中的值作为常规参数参数传递?

这就是我所拥有的:

function main
{
inputGrams($carbGrams, $fatGrams)
$carbGrams
$carbGrams
calcGrams
displayInfo
}

function inputGrams([ref]$carbGrams, [ref]$fatGrams)
{
    $carbGrams = read-host "Enter the grams of carbs per day"
    $fatGrams = read-host "Enter the grams of fat per day"
}

function calcGrams
{
    $carbCal = $carbGrams * 4
    $fatCal = $fatGrams * 9
}

function displayInfo 
{
    write-host "The total amount of carb calories is $carbCal" 
    write-host "The total amount of fat calories is $fatCal"
}

main
Run Code Online (Sandbox Code Playgroud)

inputGrams函数之后的两个值应该在每次运行脚本时更改,但由于范围问题和传递值而不会更改.任何人都知道如何正确地将这些值传递回主函数?

And*_*ndi 14

有一些问题.首先,这是一个工作示例:

function main
{
    # 1. Create empty variable first.
    New-Variable -Name carbGrams
    New-Variable -Name fatGrams

    # 2. Spaces in between parameters. Not enclosed in parens.
    # 3. Put REF params in parens.
    inputGrams ([ref]$carbGrams) ([ref]$fatGrams)

    $carbGrams
    $fatGrams
}

function inputGrams( [ref]$carbGrams, [ref]$fatGrams )
{
    # 4. Set the Value property of the reference variable.
    $carbGrams.Value = read-host "Enter the grams of carbs per day"
    $fatGrams.Value = read-host "Enter the grams of fat per day"
}

main
Run Code Online (Sandbox Code Playgroud)

并解释:

  1. 在REF传递变量之前,您需要创建变量.
  2. 不要将PowerShell函数参数括在parens中,只需用空格分隔它们即可.
  3. 将REF参数放在parens中.
  4. 要设置REF变量的值,您需要设置Value属性.

  • "价值"属性让我感到...谢谢安迪! (2认同)

小智 0

安迪走在正确的道路上,但[Ref] 很棘手,建议尽可能避免它们

\n\n

正如你所说,问题在于范围。除了main \xe2\x80\x94 之外的所有函数 \ xe2\x80\x94 都是从 main 调用的,因此您需要通过在main \ 的作用域(即它们的父作用域)中设置变量来使变量可用于这些函数,并使用 Set-变量或新变量。

\n\n

当使用 Get-Variable 检索它们的值时,同样的点也是有效的。

\n\n
function main\n{\n    inputGrams\n    $carbGrams\n    $fatGrams\n    calcGrams\n    displayInfo\n}\n\nfunction inputGrams\n{\n    # type constrain as Single because Read-Host returns a String\n    [single]$carbs = read-host "Enter the grams of carbs per day"\n    [single]$fat = read-host "Enter the grams of fat per day"\n\n    # scope 1 is the parent scope, i.e. main\'s scope\n    Set-Variable -Name carbGrams -Value $carbs -Scope 1\n    Set-Variable -Name fatGrams -Value $fat -Scope 1\n}\n\nfunction calcGrams\n{\n    # scope 1 is the parent scope, i.e. main\'s scope\n    Set-Variable -Name carbCal -Value ($carbGrams * 4) -Scope 1\n    Set-Variable -Name fatCal -Value ($fatGrams * 9) -Scope 1\n}\n\nfunction displayInfo \n{\n    # scope 1 is the parent scope, i.e. main\'s scope\n    $_carbCal = Get-Variable -Name carbCal -Scope 1 -ValueOnly\n    $_fatCal = Get-Variable -Name fatCal -Scope 1 -ValueOnly\n\n    write-host "The total amount of carb calories is $_carbCal" \n    write-host "The total amount of fat calories is $_fatCal"\n}\n\nmain\n
Run Code Online (Sandbox Code Playgroud)\n\n

PS:我希望我没有破坏你的学校作业,只是想帮忙;)

\n