powershell - 无法将参数 “address”转换为 “System.Object[]”,值 “DownloadString”键入 “System.Uri”: “Cannot convert the ” System.Object []“

标签 powershell powershell-2.0 powershell-3.0

我需要创建一个脚本来对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/

相关文章:

windows - 在 Powershell 脚本中复制命令的目的是什么?

Powershell:压缩文件

powershell - 仅获取所有字母文件扩展名

powershell - Get-Content -wait 无法按照文档中的描述工作

powershell - 为什么 $_ 在 .ps1 和 .psm1 文件中的行为不同?

sql-server - Powershell 运行 SQL 作业,延迟,然后运行下一个作业

Powershell换行符不起作用我尝试过 `n "`n"'` n'

powershell - 如何搜索包含另一个数组中的项目的对象数组?

powershell - PowerShell版本2调用WebRequest

powershell - PowerShell中的多个参数集