0

Following an answer here. I am doing the following:

param(
    # Required. Download source location (website).
     [Parameter(Mandatory=$True)]
     [URI] $URL
)
process
{
     $wc = New-Object System.Net.WebClient;
     $fileItems = $wc.downloadstring($URL) -split "<a\s+" | %{ [void]($_ -match "^HREF=[`'`"]  ([^`'`">\s]*)"); $matches[1] };
     return $fileItems;
}

I am getting the following error:

ForEach-Object : Cannot index into a null array.
At J:\LMIData\PowerShell\HTTP_based_downloader.ps1:9 char:61
+     $fileItems = $wc.downloadstring($URL) -split "<a\s+" | % <<<< { [void]($_ -match "^HREF=[`'`"]([^`'`">\s]*)"); $matches[1]; };
    + CategoryInfo          : InvalidOperation: (1:Int32) [ForEach-Object], RuntimeException
    + FullyQualifiedErrorId : NullArray,Microsoft.PowerShell.Commands.ForEachObjectCommand

The "char:61" location is right after the %.

Now, what is interesting is that this code worked previously. Is this possibly an issue in the -match regex? I have not declared the $matches array - could that be it?

I am at a loss here as I am still new to powershell. I am aware that I can get the list of links in powershell v3+ using Invoke-WebRequest but that is not an option as the system this is running on is locked at v2 for the time being.

0

1 Answer 1

2

Looks more like your download might not be what you expected. Try adding some debug.

param(
    # Required. Download source location (website).
     [Parameter(Mandatory=$True)]
     [URI] $URL
  )
  process
  {
     $wc = New-Object System.Net.WebClient;
     $Download = $wc.downloadstring($URL)
     Write-Debug "Download is $Download"
     $fileItems = $Download -split "<a\s+" | %{ [void]($_ -match "^HREF=[`'`"]  ([^`'`">\s]*)"); $matches[1] };
     return $fileItems;
  }

and set your $DebugPreference to 'Continue' amd see what your d/l payload looks like.

Sign up to request clarification or add additional context in comments.

8 Comments

As I said. I am a newbie to PS. What is $DebugPreference
If I just return $Download or if I return just $Download -split "<a\s+" I have the expected output.
What happens if you return the split and run it through that match?
Same error. It has just moved to the line where I try and do the match. If I initialize the $match like '$match = @()` I no longer get the error but I do not get an array either.
Then your regex isn't capturing anything.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.