Error Using Invoke-WebRequest in a Class

Welcome Forums General PowerShell Q&A Error Using Invoke-WebRequest in a Class

This topic contains 2 replies, has 2 voices, and was last updated by

 
Keymaster
1 year, 1 month ago.

  • Author
    Posts
  • #81413

    Participant
    Points: 0
    Rank: Member

    I'm not sure what I'm missing or if this is a bug but would appreciate thoughts.
    The script below produces an error when used in Powershell but not ISE.

    Originally I thought this might be a bug in an early version of PowerShell but I've since
    upgraded to 5.1.14409.1005 and its still happens. Oddly enough the intellisense in ISE says
    it can't find the type either but it doesn't error out on run.

    Here is the error.
    "Unable to find type [Microsoft.PowerShell.Commands.HtmlWebResponseObject]"

    Here is the body of the script. This works in ISE

    Class TestObject {
    [Microsoft.PowerShell.Commands.HtmlWebResponseObject]$WebRequest
    TestObject(){
    }
    
    [TestObject]LogOn(){
        $this.WebRequest = Invoke-WebRequest -URI http://www.bing.com?q=how+many+feet+in+a+mile
        return $this
        }
    }
    $Test = New-Object -TypeName TestObject 
    $Test.LogOn()
    
  • #81418

    Participant
    Points: 0
    Rank: Member

    It appears as if I can remove the data type definition of the $WebRequest variable and it works.
    So unless someone has anything to add I'll move on.

    Class TestObject {
    $WebRequest
    TestObject(){
    }
    
    [TestObject]LogOn(){
        $this.WebRequest = Invoke-WebRequest -URI http://www.bing.com?q=how+many+feet+in+a+mile
        return $this
        }
    }
    $Test = New-Object -TypeName TestObject 
    $Test.LogOn()
    
  • #81421

    Keymaster
    Points: 1,625
    Helping HandTeam Member
    Rank: Community Hero

    No, that was going to be my suggestion. Class namespaces get a little weird and by not using a type you just let .NET figure it out, which it's usually pretty good at.

The topic ‘Error Using Invoke-WebRequest in a Class’ is closed to new replies.