简体   繁体   English

如何将函数输出传递给powershell中的另一个函数?

[英]How to pass the function output to another function in powershell?

First time to use the PowerShell.第一次使用PowerShell。

I try to find a way to use the function output as the input of another function.我试图找到一种方法将函数输出用作另一个函数的输入。

For an example,例如,

Function TK
{
    param ([int]$OTK)

    $TK = $OTK * 2

    write-host "TK $TK"
}

Function MAT
{
    param ([int]$OMAT)

    $MAT = $OMAT * $TK /5

    write-host "MAT $MAT"
}

The idea is to create a script or a module to call different functions independently.这个想法是创建一个脚本或一个模块来独立调用不同的函数。 It starts with the first function and pass the ouput to another function as the input.它从第一个函数开始,并将输出作为输入传递给另一个函数。 The functions can either run independently or run sequentially.这些函数可以独立运行,也可以顺序运行。

Any Example?任何例子?

All output from functions is passed down the pipe.函数的所有输出都通过管道传递。 That is all output .这就是所有的输出 You are using write-host which is just for displaying on the console itself.您正在使用write-host ,它仅用于在控制台本身上显示。 Use Write-Output or just write the command out with out it.使用Write-Output或仅将命令写出而不使用它。 I also suggest you have a look at about_functions .我还建议你看看about_functions

Not exactly sure what the question is but the title as asked I would do something like this.不完全确定问题是什么,但所问的标题我会做这样的事情。

Function TK
{
    param ([int]$OTK)
    $OTK * 2
}

Function MAT
{
    param ([int]$OMAT, $TK)
    $OMAT * $TK /5
}

The line $OMAT * $TK /5 could also be read as Write-Output $OMAT * $TK /5 .$OMAT * $TK /5也可以读作Write-Output $OMAT * $TK /5 They are functionally the same.它们在功能上是相同的。

I added another parameter for the MAT function for the second value $TK .我为第二个值$TKMAT函数添加了另一个参数。 You can declare variables using the global keyword but this is clear on concise.您可以使用global关键字声明变量,但这很简洁。 This would be a sample function call which outputs the result 10这将是一个示例函数调用,它输出结果10

MAT 5 (TK 5)

The expression (TK 5) is evaluated then sent as the second value for the function MAT .表达式(TK 5)被评估,然后作为函数MAT的第二个值发送。 You can also use a variable as a middle man but unless you need to use the function calls output more than once this would be redundant.您也可以使用变量作为中间人,但除非您需要多次使用函数调用输出,否则这将是多余的。

$result = TK 5
MAT 5 $result

You can also call functions inside one another just like any cmdlet.您还可以像任何 cmdlet 一样在彼此内部调用函数。 It is important though to declare the function before you call it.在调用函数之前声明它很重要。

Function MAT
{
    param ([int]$OMAT)
    $OMAT * TK /5
}

Note the "TK" above code will call the function TK .注意上面的“TK”代码将调用函数TK

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM