首页 > 解决方案 > 循环通过 CSV 构建 URL

问题描述

首先在这里尝试使用 powershell - 我有一个像这样格式化的 CSV。

IPAddress,Username,Password
11.11.34.48,user,pass

我想使用 Powershell 循环遍历 CSV 的每一行并构建一个 URL,然后我会调用它。

$path = "D:\Users\user\Documents\DeviceFocus.csv"
$ValidHeaders = @(
        "IPAddress",
        "Username",
        "Password"
        
    )

try {
    $DeviceList = @(Import-Csv $path)
    $CSVHeaders = $DeviceList | Get-Member -MemberType NoteProperty | Select-Object -ExpandProperty Name
    foreach ($Header in $ValidHeaders) {
        if ($CSVHeaders -notcontains $Header) {
            throw [System.Management.Automation.PropertyNotFoundException] "CSV file does not contain a correct header row."
        }
    
    else {
    ##echo $DeviceList
    }
    }
    }
    catch [Exception] {
    $msg = "Failed to import CSV file $CSVFile. Detailed Exception Trace - " + $_.Exception.Message + "`r`n"
    
    throw $msg 
    }

    
   ## Setup Counter
$Count = 0
$MaxFailureCount = 3
$FailureCount = 0
$CountBegin = $CameraList.Count

while ($Count -lt $CountBegin) {
        if ($FailureCount -gt $MaxFailureCount) {
            break
        } 
        $Count++
   

    
ForEach-Object {
        {
        Invoke-WebRequest -Uri "http://$($_.Username):$($_.Password)@$($_.IPAddress)/rcp.xml?command=0x09a5&type=P_OCTET&direction=WRITE&num=1&payload=0x85000401c9020001"
        }       
                 
      }
    } 
    
    
     if ($FailureCount -gt $MaxFailureCount) {
        echo "Maximun number of failures has been reached. Halting execution."
        Write-Host "Please check your CSV file for errors and ensure your are running in a new powershell session." -BackgroundColor Yellow -ForegroundColor Red
        break
    }
    
     else {
    echo "Done2"
    }

一个问题可以防止Invoke-WebRequest我得到一个错误:

       
Invoke-WebRequest : Cannot bind parameter 'Uri'. Cannot convert value "http://:@/rcp.xml?command=0x09a5&type=P_OCTET&direction=WRITE&num=1&payload=0x85000401c9020001" to type "System.Uri". Error: "Invalid URI: The 
hostname could not be parsed."
At line:1 char:25
+ ... equest -Uri "http://$($_Username):$($_Password)@$($_IPAddress)/rcp.xm ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Invoke-WebRequest], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

该 URL 不包含 CSV IPAddressusername、中的三个参数Password。为什么不?

标签: powershellloopscsvforeachinvoke-webrequest

解决方案


在 foreach 循环中未正确构建字符串。有问题的部分是这样的:

http://$($_Username):$($_.Password)@$($_IPAddress)/rcp.xml

要访问当前对象的成员$_,必须有一个句点分隔$_和成员。像这样,

http://$($_.Username):$($_Password)@$($_.IPAddress)/rcp.xml

更重要的是,CSV数据似乎根本没有被使用。它被读入一个变量$DeviceList = @(Import-Csv $path),但之后就不再使用了。有一个foreach-object循环,但没有被告知迭代$DeviceList's 的内容。改用. foreach($object in $collection){} _ 像这样,

foreach($device in $DeviceList) {
        Invoke-WebRequest -Uri "http://$($device.Username):$($device.Password)@$($device.IPAddress)/rcp.xml?command=0x09a5&type=P_OCTET&direction=WRITE&num=1&payload=0x85000401c9020001"
}       

为了进一步提高可读性和调试,请先使用复合格式构建字符串,然后再调用Invoke-WebRequest。像这样,

$queryParam = "?command=0x09a5&type=P_OCTET&direction=WRITE&num=1&payload=0x85000401c9020001"
foreach($device in $DeviceList) {
    $url = $("http://{0}:{1}@{2}/rpc.xml" -f $device.Username, $device.Password, $device.IPAddress, $queryParam)
    # For debugging:
    # write-host $url
    Invoke-WebRequest -Uri $url
}

推荐阅读