As I’m trying to improve OnedriveMapper, I’ve been looking into methods to avoid using Browser Emulation to authenticate with Office 365.
This wasn’t difficult, but storing the cookie posed a challenge. There are no available methods in Powershell to do so, thus I went searching until I ran into a post on Stackoverflow that shows how to store a cookie using C#
Since Powershell can eat C#, this ended up being my working code to set a persistent OS cookie from Powershell:
$source=@"
using System.Runtime.InteropServices;
using System;
namespace Cookies
{
public static class setter
{
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool InternetSetCookie(string url, string name, string data);
public static bool SetWinINETCookieString(string url, string name, string data)
{
bool res = setter.InternetSetCookie(url, name, data);
if (!res)
{
throw new Exception("Exception setting cookie: Win32 Error code="+Marshal.GetLastWin32Error());
}else{
return res;
}
}
}
}
"@
$compilerParameters = New-Object System.CodeDom.Compiler.CompilerParameters
$compilerParameters.CompilerOptions="/unsafe"
Add-Type -TypeDefinition $source -Language CSharp -CompilerParameters $compilerParameters
[DateTime]$dateTime = Get-Date
$dateTime.AddDays(1)
$str = $dateTime.ToString("R")
[Cookies.setter]::SetWinINETCookieString("https://cookieURL","cookieNAME","value;Expires=$str")
edit: don’t use the Get-Hotfix PS command before you run above code, for some reason it breaks things.
Hi,
I am the only one that cannot make this code work? IE11 cannot create file cookies anymore :
https://answers.microsoft.com/en-us/ie/forum/ie11-iewindows_10/ie11-normal-cookies-are-gone-since-creators-fall/7f2b38a0-aeaf-4c4b-a53f-dd438fdc20cd
Will this fix the issue with Azure AD Connect so that the SSO keys can be added back in to GPO’s?
Hi!
I did some troubleshooting of the commands above as it failed for me.
I was using the Powershell commandlet Test-connection and after removing that, the cookie part worked as expected.