【问题标题】:Loop through CSV to build URL循环通过 CSV 构建 URL
【发布时间】:2021-11-05 19:18:12
【问题描述】:

首先在这里尝试使用 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

网址不包含来自 CSV 文件的三个参数IPAddressusernamePassword。为什么不呢?

【问题讨论】:

    标签: powershell loops csv foreach invoke-webrequest


    【解决方案1】:

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

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

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

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

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

    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
    }
    

    【讨论】:

    • 我添加了句点,但它似乎并没有改变它的运作方式。我尝试write-output "http://$($_.Username):$($_.Password)@$($_.IPAddress)/rcp.xml?command=0x09a5&type=P_OCTET&direction=WRITE&num=1&payload=0x85000401c9020001",但它的打印结果与显示的完全一样。
    猜你喜欢
    • 1970-01-01
    • 2019-07-20
    • 1970-01-01
    • 2015-03-01
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    相关资源
    最近更新 更多