Unable to load adalsql.dll error when calling `Invoke-sqlcmd`

So, this problem vexed me as well. I'm unclear as to how it happened, but maybe it's just coincidence that it happened when I installed the latest version of SSMS. My fix was to:

  1. Navigate to Add or Remove Programs

  2. In the little search window type sql, or just go find: "Active Directory Authentication Library for SQL Server".

Note: This will not be in Windows' installed programs list if you have installed Visual Studio 2019. You can run the same installer by invoking MsiExec.exe /I{6BF11ECE-3CE8-4FBA-991A-1F55AA6BE5BF} from a command prompt.

  1. Uninstall that little guy

  2. Navigate here and download the latest ADAL library (pick x64):
    https://www.microsoft.com/en-us/download/confirmation.aspx?id=48742

  3. Just for kicks, reboot

  4. Your stuff should now properly load adalsql.dll!

Update #3, 2020-07-13: Installing the older version works, but is vulnerable to being clobbered by the SSMS and VS2019 installers. The reason the new version of ADAL doesn't work is because its installer fails to add a registry entry pointing to the 64-bit version of adal.dll. I added an answer below which includes the missing registry value, which you can add yourself. Once that's done, you should never need to do this dance again. - @Tullo_x86


In my case culprit was VS 2019. It has newer version of ADALSQL package. For me it was at path "C:\ProgramData\Microsoft\VisualStudio\Packages\sql_adalsql,version=16.0.61903.25110,chip=x64,language=en-US", which I uninstalled and installed desired version to resolve the issue.

Hope this helps!


The bewilderingly simple solution to this annoying problem

  1. Ensure you actually have ADAL installed (the existence of C:\Windows\system32\adal.dll is plenty)

  2. Paste this into a .reg file:

     Windows Registry Editor Version 5.00
    
     [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSADALSQL]
     "TargetDir"="C:\\Windows\\System32\\adal.dll"
    
  3. Double-click the .reg file to install that value

You're done. Go celebrate!

Explain WTF is going on. Why this is necessary?

This error happens because the .NET adapter for SQL Server can't find adal.dll. But why is this? It's installed, right?

Well, the installer for the latest version of ADAL (packaged with VS 2019 and the latest version of SQL Server Management Studio) adds a registry entry for the 32-bit version of the DLL (at C:\Windows\SysWOW64\adal.dll), but does not add the entry for the 64-bit version (which gets installed to C:\Windows\system32\adal.dll). If you build and run your application in 32-bit mode, you'll never see this bug manifest.

This is simply a bug in the ADAL installer. Presumably it wasn't detected by Microsoft because both Visual Studio and SSMS are 32-bit applications and thus don't go looking for the 64-bit version.