【问题标题】:Return an array from a function in PowerShell 3.0从 PowerShell 3.0 中的函数返回数组
【发布时间】:2015-12-12 06:27:32
【问题描述】:

我正在尝试让 PowerShell 3.0 从函数返回一个数组。不幸的是,这没有很好的记录,因为我过去两天一直在谷歌搜索这方面的例子。我已经接近用 C# 重写整个脚本并称之为一天了。

脚本检查包含在变量中的一组 URL。有问题的函数从数组中获取 URL 列表并循环遍历数组,将 HTTP 状态代码添加到新数组中。该函数执行上述所有操作,但它不返回数组。这是有问题的功能:

function URLCheck ($URLStatusCode)
{
    foreach($uri in $URLStatusCode )
    {
        $result = @()
        $time = try
        {
            $request = $null
            ## Check response time of requested URI.
            $result1 = Measure-Command { $request = Invoke-WebRequest -Uri $uri}
            $result1.TotalMilliseconds
        }
        catch
        {
            <# If request generates exception such as 401, 404 302 etc,
            pull status code and add to array that will be emailed to users #>
            $request = $_.exception.response
            $time = -1
        }
        $result += [PSCustomObject] @{
            Time = Get-Date;
            Uri = $uri;
            StatusCode = [int] $request.StatusCode; 
            StatusDescription = $request.StatusDescription; 
            ResponseLength = $request.RawContentLength; 
            TimeTaken =  $time;
        }
    }
    return $result
}

我这样称呼:

URLCheck $LinuxNonProdURLList
$result

执行后我还打印了 $result 的内容,我注意到它是空的。但是,如果我将 return 语句放在 foreach 循环中,它确实会将信息发送到控制台。

任何帮助将不胜感激。

【问题讨论】:

    标签: arrays powershell powershell-3.0


    【解决方案1】:

    经过更多的故障排除后,我发现数组 $result 只是函数的本地。我在 foreach 循环之外声明了数组并修复了错误。这是更新的代码:

    function URLCheck ($URLStatusCode)
    {
        $result = @()
        foreach($uri in $URLStatusCode )
        {
            $time = try
            {
                $request = $null
                ## Check response time of requested URI.
                $result1 = Measure-Command { $request = Invoke-WebRequest -Uri $uri}
                $result1.TotalMilliseconds
            }
            catch
            {
                <# If request generates exception such as 401, 404 302 etc,
                pull status code and add to array that will be emailed to users #>
                $request = $_.exception.response
                $time = -1
            }
            $result += [PSCustomObject] @{
                Time = Get-Date;
                Uri = $uri;
                StatusCode = [int] $request.StatusCode; 
                StatusDescription = $request.StatusDescription; 
                ResponseLength = $request.RawContentLength; 
                TimeTaken =  $time;
            }
        }
        return $result
    }
    

    【讨论】:

    • 只是一个快速的 PowerShell 说明。您可能会丢失 $result+= 和 return 语句,并且该函数的工作方式相同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    • 2012-08-17
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 2015-02-09
    • 2015-10-12
    相关资源
    最近更新 更多