无法转换参数“address”,使用值:“System.Object []”,“DownloadString”键入“System.Uri”:“无法转换”System.Object []“

时间:2017-10-06 09:53:51

标签: powershell powershell-v2.0 powershell-v3.0

我需要创建一个脚本来在3个不同的环境网址上发出请求,然后为我发送的每个页面生成一个CSV文件,其中包含每个环境的平均响应时间。

但是我收到了这个错误:

  

无法转换参数“address”,其值为:“System.Object []”,for   “DownloadString”键入“System.Uri”:“无法转换   键入“System.Object []”类型的“System.Object []”值   “的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

1 个答案:

答案 0 :(得分:4)

你在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'