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:

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());
                return res;

$compilerParameters = New-Object System.CodeDom.Compiler.CompilerParameters

Add-Type -TypeDefinition $source -Language CSharp -CompilerParameters $compilerParameters

[DateTime]$dateTime = Get-Date
$str = $dateTime.ToString("R")


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
Sort by:   newest | oldest | most voted

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