将powershell函数更改为带有Invoke WebRequest的类时出现问题

将powershell函数更改为带有Invoke WebRequest的类时出现问题,powershell,oop,invoke-webrequest,Powershell,Oop,Invoke Webrequest,我希望能得到一些帮助。我目前正在将我的一些函数转换为自定义类方法。在我继续学习本系列教程的过程中,一切都进展顺利 我面临的问题是与 -SessionVariable mySession 然后在我的第二个请求中引用它 -WebSession $mySession 这是我的类ps1文件 Class myClass { [String]$url = "http://httpbin.org/json" [String]$username = "us

我希望能得到一些帮助。我目前正在将我的一些函数转换为自定义类方法。在我继续学习本系列教程的过程中,一切都进展顺利

我面临的问题是与

-SessionVariable mySession
然后在我的第二个请求中引用它

-WebSession $mySession
这是我的类ps1文件


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()
我尝试过各种方法,比如在类的顶部添加mySession变量和URL。在方法顶部声明
$mySession

我可以在我的调试器(vs代码)中将其设置为自动变量,但不知道如何访问它

如果我使用一个标准函数,它会像预期的那样工作,将代码提升并转移到一个类中会让我毛骨悚然

如果这不是一个好方法,我愿意接受其他方法

谢谢你的帮助:)

参见@zett42评论

我在测试中遇到的问题是,我将mySession作为类属性,所以当我试图在方法中引用它时,它抱怨我必须使用$this.mySession

这是正确的错误,但以错误的结果结尾,因为$This.mySession为null

从类属性中删除它并在方法中声明,正如zett42指出的那样。如果其他人感兴趣,我的示例如下所示

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()

$mySession=$null
getWebSite()
方法的开头应该可以工作。非常感谢。我现在明白我的错误了。当我试图让它自己工作时,我将
$mySession
作为类属性。计算机抱怨说我不得不使用
$this.mySession
将其从顶部删除,然后让您的建议生效:)我在这上面花的时间太长了>:(
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()