0

First try at powershell here - I have a CSV formatted like this.

IPAddress,Username,Password
11.11.34.48,user,pass

I want to use Powershell to loop through each row of the CSV and build a URL which i then invoke.

$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"
    }

A problem prevents the Invoke-WebRequest I get an error:

       
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

The URL doesn't include the three parameters from the CSV IPAddress, username, Password. Why not?

Display Name
  • 405
  • 6
  • 26

1 Answers1

1

The string is not being built properly in the foreach loop. Problematic part is this:

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

To access member of current object $_, there must be a period separating $_ and the member. Like so,

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

What's more, the CSV data doesn't seem to be used at all. It is read into a variable $DeviceList = @(Import-Csv $path), but after that it is not used. There is a foreach-object loop, but it's not being told to iterate the $DeviceList's contents. Use a foreach($object in $collection){} instead. Like so,

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"
}       

For further improvement in readability and debugging, build the string first with composite formatting and call Invoke-WebRequest later. Like so,

$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
}
vonPryz
  • 22,996
  • 7
  • 54
  • 65
  • I added the period but it didn't seem to change how it operates. I tried to `write-output "http://$($_.Username):$($_.Password)@$($_.IPAddress)/rcp.xml?command=0x09a5&type=P_OCTET&direction=WRITE&num=1&payload=0x85000401c9020001"` but it prints exactly as displayed. – Display Name Sep 10 '21 at 04:43