diff --git a/changelogs/fragments/powershell-addtype-env-vars.yml b/changelogs/fragments/powershell-addtype-env-vars.yml new file mode 100644 index 00000000000..6c0d73c3cb8 --- /dev/null +++ b/changelogs/fragments/powershell-addtype-env-vars.yml @@ -0,0 +1,2 @@ +bugfixes: +- PowerShell - Ignore the ``LIB`` environment variable when compiling C# Ansible code diff --git a/lib/ansible/module_utils/powershell/Ansible.ModuleUtils.AddType.psm1 b/lib/ansible/module_utils/powershell/Ansible.ModuleUtils.AddType.psm1 index ba38159d5f1..a4801ba5d5f 100644 --- a/lib/ansible/module_utils/powershell/Ansible.ModuleUtils.AddType.psm1 +++ b/lib/ansible/module_utils/powershell/Ansible.ModuleUtils.AddType.psm1 @@ -332,7 +332,28 @@ Function Add-CSharpType { # compile the code together and check for errors $provider = New-Object -TypeName Microsoft.CSharp.CSharpCodeProvider - $compile = $provider.CompileAssemblyFromDom($compile_parameters, $compile_units) + + # This calls csc.exe which can take compiler options from environment variables. Currently these env vars + # are known to have problems so they are unset: + # LIB - additional library paths will fail the compilation if they are invalid + $originalEnv = @{} + try { + 'LIB' | ForEach-Object -Process { + $value = Get-Item -LiteralPath "Env:\$_" -ErrorAction SilentlyContinue + if ($value) { + $originalEnv[$_] = $value + Remove-Item -LiteralPath "Env:\$_" + } + } + + $compile = $provider.CompileAssemblyFromDom($compile_parameters, $compile_units) + } + finally { + foreach ($kvp in $originalEnv.GetEnumerator()) { + [System.Environment]::SetEnvironmentVariable($kvp.Key, $kvp.Value, "Process") + } + } + if ($compile.Errors.HasErrors) { $msg = "Failed to compile C# code: " foreach ($e in $compile.Errors) { diff --git a/test/integration/targets/module_utils_Ansible.ModuleUtils.AddType/library/add_type_test.ps1 b/test/integration/targets/module_utils_Ansible.ModuleUtils.AddType/library/add_type_test.ps1 index d89f99b79a4..d6b05691191 100644 --- a/test/integration/targets/module_utils_Ansible.ModuleUtils.AddType/library/add_type_test.ps1 +++ b/test/integration/targets/module_utils_Ansible.ModuleUtils.AddType/library/add_type_test.ps1 @@ -295,5 +295,28 @@ namespace Namespace11 Add-CSharpType -Reference $arch_class Assert-Equals -actual ([Namespace11.Class11]::GetIntPtrSize()) -expected ([System.IntPtr]::Size) +$lib_set = @' +using System; + +namespace Namespace12 +{ + public class Class12 + { + public static string GetString() + { + return "b"; + } + } +} +'@ +$env:LIB = "C:\fake\folder\path" +try { + Add-CSharpType -Reference $lib_set +} +finally { + Remove-Item -LiteralPath env:\LIB +} +Assert-Equals -actual ([Namespace12.Class12]::GetString()) -expected "b" + $result.res = "success" Exit-Json -obj $result