我试图让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循环中,它会将信息发送到控制台。
非常感谢任何帮助。
答案 0 :(得分: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
}