2015-09-15 34 views
0

我試圖讓PowerShell 3.0從函數返回數組。不幸的是,這並沒有很好的記錄,因爲我在過去兩天花了很多時間在Google上搜索相關示例。我正在接近用C#重寫整個腳本並且每天都在調用它。從PowerShell 3.0中的函數返回數組

腳本檢查包含在變量中的一組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 

我還印製的$內容的執行結果後,我發現它是空的。但是,如果我要將return語句放在foreach循環中,它會將信息發送到控制檯。

任何幫助將不勝感激。

回答

0

經過一些更多的疑難解答後,我發現數組$ 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 
} 
+3

只是一個快速的PowerShell筆記。您可能會失去$ result + =,並且return語句和函數的工作方式相同。 –