Setting a Windows Cookie with Powershell (using InternetSetcookie in WinInet)

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.

Leave a Reply

5 Comments on "Setting a Windows Cookie with Powershell (using InternetSetcookie in WinInet)"

Notify of
avatar
Sort by:   newest | oldest | most voted
Paul
Guest

Will this fix the issue with Azure AD Connect so that the SSO keys can be added back in to GPO’s?

wpDiscuz