【发布时间】: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