Reusing SessionVariables from Invoke-Webrequest between Functions

This topic contains 1 reply, has 2 voices, and was last updated by  Sam Boutros 1 month ago.

  • Author
    Posts
  • #77712

    Wei-Yen Tan
    Participant

    Okay so I know that we can reuse a session variable made with Invoke-Webrequest in an nteractive shell....but what if we have a session that we want to reuse elsewhere.

    I am working on a module for the web application Thruk:

    function Connect-Thrukwebsite
    {
    	[CmdletBinding()]
    	param
    	(
    		[Parameter(Position = 0)]
    		[string]$uri,
    		[Parameter(Position = 1)]
    		[pscredential]$credential
    	)
    	
    	
            $login = Invoke-WebRequest "$uri/cgi-bin/login.cgi" -SessionVariable thruk
            $login.Forms[0].Fields.login = $cred.UserName
            $login.Forms[0].Fields.password = $cred.GetNetworkCredential().Password
        
            $mainPage = Invoke-WebRequest ("https://$uri/thruk/cgi-bin/login.cgi") -WebSession $thruk -Body $login.Forms[0].fields
            -Method Post 
           
    }
    
    

    What I would like is to reuse that Thruk session variable in other parts of powershell. Is there anyway that I can do that? I tried to do a global variable (just to play) but it didnt work. Help is most appreciated.

  • #77713

    Sam Boutros
    Participant
    function Connect-Thrukwebsite
    {
    	[CmdletBinding()]
    	param
    	(
    		[Parameter(Position = 0)]
    		[string]$uri,
    		[Parameter(Position = 1)]
    		[pscredential]$credential
    	)
    	
    	
            $login = Invoke-WebRequest "$uri/cgi-bin/login.cgi" -SessionVariable thruk 
            $login.Forms[0].Fields.login = $cred.UserName
            $login.Forms[0].Fields.password = $cred.GetNetworkCredential().Password
        
            $mainPage = Invoke-WebRequest ("https://$uri/thruk/cgi-bin/login.cgi") -WebSession $thruk -Body $login.Forms[0].fields -Method Post 
    
            $thruk # You pass variable from function to main script by simply placing it in the pipeline
           
    }
    
    $URI = 'demo.thruk.org'
    $Cred = Get-Credential # admin/admin
    
    $thruk = Connect-Thrukwebsite -uri $URI -credential $Cred # Receives data from function
    
    'Here''s your session variable:'
    $thruk 
    

You must be logged in to reply to this topic.