簡體   English   中英

從PowerShell 3.0中的函數返回數組

[英]Return an array from a function in PowerShell 3.0

我試圖讓PowerShell 3.0從函數返回數組。 不幸的是,這並沒有得到很好的記錄,因為我在過去的兩天中一直在搜索Google的示例。 我現在差不多要用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循環中,它將把信息發送到控制台。

任何幫助將不勝感激。

經過更多的故障排除后,我發現數組$ 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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM