PowerShell "Add-Type" compile error in CI
Add-Type tried to compile inline C# (or VB) and failed. The compiler reported errors, a referenced assembly was missing, or the runtime lacked a usable compiler.
What this error means
Add-Type aborts with "Cannot add type. There were compilation errors." and lists C# error codes. Deterministic for a given source string and runtime.
Add-Type : Cannot add type. There were compilation errors.
At line:1 char:1
+ Add-Type -TypeDefinition $source
+ CategoryInfo : InvalidData: (...) [Add-Type], InvalidOperationException
+ FullyQualifiedErrorId : COMPILER_ERRORS,Microsoft.PowerShell.Commands.AddTypeCommand
error CS0246: The type or namespace name 'JsonConvert' could not be foundDiagnose it: which runtime is actually on PATH?
Runners ship multiple versions of most runtimes and select one through a version manager. When a setup action and a version file disagree, the resulting error is about your code rather than the version.
which -a <runtime>
<runtime> --version
echo "PATH=$PATH" | tr ":" "\n" | head -20
# does a version file in the repo disagree with the workflow?
cat .tool-versions .nvmrc .ruby-version .python-version 2>/dev/nullCommon causes
A required assembly was not referenced
Inline C# that uses a type outside the default references fails to compile until you add the assembly via -ReferencedAssemblies.
API differs between Windows PowerShell and PowerShell 7
Code compiled fine under .NET Framework (PowerShell 5.1) may not compile under .NET (PowerShell 7) because the available APIs differ.
How to fix it
Reference the assemblies the code needs
Pass the required assemblies explicitly so the type resolves at compile time.
Add-Type -TypeDefinition $source `
-ReferencedAssemblies 'System.Net.Http','System.Text.Json'Pin the PowerShell edition for the step
- Decide whether the C# targets .NET Framework (powershell: / 5.1) or .NET (pwsh: / 7).
- Run the Add-Type step under that edition consistently so the available APIs match.
- Surface the real compiler error with $error[0].Exception.Message for the exact CS code.
How to prevent it
- Reference required assemblies explicitly and run Add-Type under a fixed PowerShell edition so the available .NET APIs are predictable.