Author Posts

August 21, 2017 at 6:48 am

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.

August 21, 2017 at 7:46 am

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