我需要创建一个脚本来对3个不同的环境url发出请求,然后为我发送的每个页面生成一个CSV文件,其中包含每种环境的平均响应时间。
但是我得到这个错误:
Cannot convert argument "address", with value: "System.Object[]", for "DownloadString" to type "System.Uri": "Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Uri".
这是我的代码:
function ResponseTime($CommonName,$URL, $environment)
{
$Times = 5
$i = 0
$TotalResponseTime = 0
While ($i -lt $Times) {
$Request = New-Object System.Net.WebClient
$Request.UseDefaultCredentials = $true
$Start = Get-Date
$PageRequest = $Request.DownloadString($URL)
$TimeTaken = ((Get-Date) - $Start).TotalMilliseconds
$Request.Dispose()
$i ++
$TotalResponseTime += $TimeTaken
}
$AverageResponseTime = $TotalResponseTime / $i
Write-Host Request to $CommonName took $AverageResponseTime ms in average -ForegroundColor Green
$details = @{
Date = get-date
AverageResponseTime = $AverageResponseTime
ResponseTime = $Destination
Environment = $environment
}
$results += New-Object PSObject -Property $details
}
ResponseTime 'app homepage' 'https://urlproduction', 'PRODUCTION'
ResponseTime 'app homepage' 'https://urlQA', 'QA'
ResponseTime 'app homepage' 'https://urltest', 'TEST'
$results | export-csv -Path c:\so.csv -NoTypeInformation
最佳答案
您在Powershell中遇到了一个常见的陷阱。以为函数参数在定义中用逗号分隔,而函数调用参数没有。如果使用逗号,Powershell会将这些项目转换为数组。
在这种情况下
ResponseTime 'app homepage' 'https://urlproduction', 'PRODUCTION'
被解析为
Call function ResponseTime with two parameters:
'app homepage'
和'https://urlproduction', 'PRODUCTION'
-后者是由两个元素组成的数组。另一方面
ResponseTime 'app homepage' 'https://urlproduction' 'PRODUCTION'
被解析为
Call function ResponseTime with three parameters:
'app homepage'
,'https://urlproduction'
和'PRODUCTION'
关于powershell - 无法将参数 “address”转换为 “System.Object[]”,值 “DownloadString”键入 “System.Uri”: “Cannot convert the ” System.Object []“,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46603056/