Error Using Invoke-WebRequest in a Class

This topic contains 2 replies, has 2 voices, and was last updated by  Don Jones 1 week, 6 days ago.

  • Author
    Posts
  • #81413

    Greg Tate
    Participant

    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

    Greg Tate
    Participant

    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

    Don Jones
    Keymaster

    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.

You must be logged in to reply to this topic.