I am currently logged in with my browser and wanted to get the current cookie of that session. but when i use this code it creates another session id for that request only. NOT for the currently logged in session in my browser.
$url = "http://example.website/"
$cookiejar = New-Object System.Net.CookieContainer
$webrequest = [System.Net.HTTPWebRequest]::Create($url);
$webrequest.CookieContainer = $cookiejar
$response = $webrequest.GetResponse()
$cookies = $cookiejar.GetCookies($url)
foreach ($cookie in $cookies) {
Write-Host "$($cookie.name) = $($cookie.value)"
}
i wanted to output the similar session id cookie in my browser and with the script.
As Lee_Dailey suggests, you can use the IE COM object interface, however the cookie details are limited. The details are returned as a String which can be converted into a hashtable to get key,value pairs - but extended information such as domain or expiration will not be available.
This will only work for Internet Explorer and I am not certain how complete the information is, for example whether Secure cookies can be retrieved this way, so you will need to test.
Depending on your requirements, this may or may not be sufficient.
#URL we want to retrieve cookie information from
$URL = 'https://stackoverflow.com'
#Hashtable to store the cookie details
$CookieDetails = @{}
#Create a shell object
$Shell = New-Object -ComObject Shell.Application
#Find the web browser tab that starts with our URL
$IE = $Shell.Windows() | Where-Object { $_.Type -eq "HTML Document" -and $_.LocationURL -like "$URL*"}
#Split the cookie string and for each line parse into k,v pairs
foreach($Line in ($IE.Document.cookie -split "; "))
{
$Line = $Line -split "="
$CookieDetails.($Line[0]) = $Line[1..-1] -join "="
}
#Output the hashtable result
$CookieDetails