I was hoping I could get some help. Im currently converting some of my functions into a custom class method. Things have been going ok while I follow along with this tutorial series.
The issue I am facing is with the
-SessionVariable mySession
and then referencing it in my second request.
-WebSession $mySession
Here is my class ps1 file
Class myClass
{
[String]$url = "http://httpbin.org/json"
[String]$username = "username"
[String]$password = "password"
getWebSite()
{
$result = Invoke-WebRequest $this.url -SessionVariable mySession
$result.RawContent | out-file "website.txt"
$result = Invoke-WebRequest -WebSession $mySession
}
}
$myRecord = new-object myClass
$myRecord.getWebSite()
+ $result = Invoke-WebRequest -WebSession $mySession
+ ~~~~~~~~~~
Variable is not assigned in the method.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : VariableNotLocal
I have tried all kinds like adding mySession variable at the top in the class along with URL. Declaring $mySession
at the top of the method
I can see it being set in my debugger(vs code) as an auto var but have no clue how I can access it.
If I use a standard function this works as expected, lifting and shifting the code into a class has me tearing my hair out.
If this isn't a good approach I am open to alternatives.
Thanks for any help :)
See @zett42 comment.
The issue I was having in testing was that I had mySession as a class property so when I was trying to reference it in the method it was complaining that I had to use $this.mySession.
This is correct error but ends in the wrong result as $this.mySession is null.
Removing it from the class properties and making the declaration in the method as zett42 points out works. My example now looks like the following if anyone else is interested.
Class myClass
{
[String]$url = "http://httpbin.org/json"
[String]$username = "username"
[String]$password = "password"
getWebSite()
{
$mySession = $null
$result = Invoke-WebRequest $this.url -SessionVariable mySession
$result.RawContent | out-file "website.txt"
$result = Invoke-WebRequest -WebSession $mySession
}
}
$myRecord = new-object myClass
$myRecord.getWebSite()