gpt4 book ai didi

powershell - 将函数的结果返回到运行时脚本

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

我有两个Powershell脚本,一个具有检查变量“名称”(作为参数传递)的值的功能。如果不匹配“John”,则结果为2,否则结果为0(包含在函数中)。

这是功能脚本:

Function test {

Param (
$name = $(throw "need -name"),
$result = 0
)

Process {
if($name -ne "John") {
Write-Host "Name is incorrect"
$result = 2
} else {
Write-Host "Student is correct"
}
}
}

第二个脚本调用此函数,并以-
Import-Module C:\function.ps1
test -name Sandra

现在,我想将结果(或状态)返回到该函数的第二个脚本中,并根据结果将更多条件添加到第二个脚本中。要实现此目的,脚本或函数需要进行哪些更改?

最佳答案

似乎您是PowerShell的新手,所以这里有一些提示:

  • 您应该使用Approved Verbs e。 G。改变你的功能
    命名为Test-StudentName
  • 有一个language integrated support for parameter handling
  • Using Write-Host is almost always wrong

  • 所以您的脚本可能看起来像这样:
    function Test-StudentName
    {
    [CmdletBinding()]
    [OutputType([int])]
    Param
    (
    [Parameter(Mandatory=$true, Position=0)]
    [ValidateNotNullOrEmpty()]
    [string]
    $Name
    )

    if ($name -ne 'John')
    {
    Write-Output 2
    }
    else
    {
    Write-Output 0
    }
    }

    关于powershell - 将函数的结果返回到运行时脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34172518/

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