无法转换参数“地址”,值为:“System.Object []”,为“DownloadString”键入“System.Uri”:“无法转换”System.Object []“
问题描述:
我需要创建一个脚本使在3个不同的环境URL的请求,然后生成与每个环境的平均响应时间的CSV文件,我发送的每个页面无法转换参数“地址”,值为:“System.Object []”,为“DownloadString”键入“System.Uri”:“无法转换”System.Object []“
但是我得到这个错误:
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 paremters:
'app homepage'
和'https://urlproduction', 'PRODUCTION'
- 其中后来是由两个元件的阵列。
在另一方面
ResponseTime 'app homepage' 'https://urlproduction' 'PRODUCTION'
被解析为
Call function ResponseTime with three paremters:
'app homepage'
,'https://urlproduction'
和'PRODUCTION'
为什么你有HTTPS之间的逗号:字符串//部分和“生产'... ? *提示* – t0mm13b
另外,将网址转换为'[System.Uri]'。 – t0mm13b