Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Could not load file or assembly 'System.Security.Principal.Windows, Version=4.1.1.0 #115326

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
ddey2000 opened this issue May 6, 2025 · 1 comment
Labels
area-System.Runtime untriaged New issue has not been triaged by the area owner

Comments

@ddey2000
Copy link

ddey2000 commented May 6, 2025

Description

I have an application that targets both .NET Framework 4.6.2 and .NET 6. The application includes functionality to execute PowerShell scripts, and this works as expected across all supported platforms—except on machines running Windows 11 24H2. On this OS version, the specific script Get-AppxPackage fails with the exception shown below, while other PowerShell scripts continue to run successfully.
The application includes System.Security.Principal.Windows.dll version 5.0.0, which is bundled in the installation path.

public PowershellExecutionResponse ExecutePowershellScript(string scriptCommand, int timeout)
{
    this.logger.LogInformation("PowerShell execution started");
    var response = new PowershellExecutionResponse
    {
        Results = new List<string>(),
        Errors = string.Empty,
        TerminatingError = string.Empty,
        ResultsProperties = new Dictionary<string, Dictionary<string, string>>(),
        ExitCode = -1
    };

    var powerShellHost = new PowershellHost();

    using (var powerShellRunSpace = RunspaceFactory.CreateRunspace(powerShellHost))
    {
        powerShellRunSpace.Open();

        var proxy = powerShellRunSpace.SessionStateProxy;

        // Prepend the executable's directory to the PSModulePath, so it will find the correct modules to import.
        var dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        var psModulePath = proxy.GetVariable(EnvPsModulePath);
        proxy.SetVariable(EnvPsModulePath, $@"{dir};{psModulePath}");

        var watch = Stopwatch.StartNew();

        using (var powerShell = PowerShell.Create())
        {
            powerShell.Runspace = powerShellRunSpace;

            var outputCollection = new PSDataCollection<PSObject>();
            powerShell.AddScript(scriptCommand);
            IAsyncResult powershellExecutionResult = powerShell.BeginInvoke<PSObject, PSObject>(
                null,
                outputCollection);

            powershellExecutionResult.AsyncWaitHandle.WaitOne(new TimeSpan(0, 0, timeout));

            if (!powershellExecutionResult.IsCompleted)
            {
                watch.Stop();
                response.ExecutionStatus = ExecutionStatus.Failure;
                response.Errors = "PowerShell script execution timeout.";
                response.ExitCode = (int)HttpStatusCode.RequestTimeout;
                response.ErrorCode = PowershellErrorCode.ScriptTimedOut;
                return response;
            }

            watch.Stop();
            response.ExecutionTime = watch.ElapsedMilliseconds;

            using (var enumerator = outputCollection.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    response.Results.Add(enumerator?.Current?.ToString());

                    // try to get ps property , but its failure should not fail the execution.
                    try
                    {
                        // Getting all Properties for each result
                        if (enumerator.Current?.Properties != null)
                        {
                            var propertiesDictionary = new Dictionary<string, string>();

                            foreach (var prop in enumerator.Current.Properties)
                            {
                                try
                                {
                                    if (prop is PSScriptProperty)
                                    {
                                        //It is permitted to subclass PSScriptProperty but there is no established scenario. So skipping this property
                                        continue;
                                    }

                                    propertiesDictionary.Add(prop.Name, Convert.ToString(prop.Value));
                                }
                                // Ignoring properties that throw exception on calling prop.Value
                                // Since these properties are not gettable.
                                catch (Exception e)
                                {
                                    this.logger.LogDebug(e, "Error while getting PowerShell property");
                                }
                            }

                            // Adding properties as a dictionary with each result.
                            response.ResultsProperties.Add(enumerator.Current.ToString(), propertiesDictionary);
                        }
                    }
                    catch (Exception e)
                    {
                        this.logger.LogDebug(e, "Error while getting PowerShell property");
                    }
                }
            }

            foreach (var error in powerShell.Streams.Error.ReadAll())
            {
                response.Errors += error;
            }

            response.TerminatingError = powerShell.InvocationStateInfo?.Reason?.ToString();
            this.logger.LogInformation("The PowerShell Exit code is : {ExitCode}", powerShellHost.ExitCode);
            response.ExitCode = powerShellHost.ExitCode;

            if (!string.IsNullOrWhiteSpace(response.Errors))
            {
                this.logger.LogError("Errors while executing script : {Errors}", response.Errors);
                response.ExecutionStatus = ExecutionStatus.Failure;

                // If exit code is not defined in script send the error code which PowerShell.exe returns i.e. 1
                if (!powerShellHost.IsExitCodeSet)
                {
                    this.logger.LogInformation("The PowerShell Exit code is : {ExitCode} due to errors in script.", powerShellHost.ExitCode);
                    response.ErrorCode = PowershellErrorCode.PowershellExecutorError;
                    response.ExitCode = 1;
                }

                return response;
            }

            if (!string.IsNullOrWhiteSpace(response.TerminatingError))
            {
                this.logger.LogError("Terminating Errors while executing script : {Errors}", response.Errors);

                // If exit code is not defined in script send the error code which PowerShell.exe returns i.e. 1
                if (!powerShellHost.IsExitCodeSet)
                {
                    this.logger.LogInformation("The PowerShell Exit code is : {ExitCode} due to runtime error in script.", powerShellHost.ExitCode);
                    response.ErrorCode = PowershellErrorCode.PowershellExecutorError;
                    response.ExitCode = 1;
                }
            }

            response.ExecutionStatus = ExecutionStatus.Success;
            this.logger.LogInformation("PowerShell execution completed");
        }

        powerShellRunSpace.Close();
    }
    return response;
}

Error: Could not load file or assembly 'System.Security.Principal.Windows, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Reproduction Steps

  1. Create an executable with the given code.
  2. Run the exe in a Windows 11 24H2 device.

Expected behavior

The application should run the given script. (Get-AppxPackage)

Actual behavior

It gives runtime exception - Could not load file or assembly 'System.Security.Principal.Windows, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040).

Regression?

No response

Known Workarounds

If we paste the System.Security.Principal.Windows.dll (Version = 4.1.1.0) in the current application directory then it's working. But I require System.Security.Principal.Windows.dll (Version = 5.0.0.0) in my application due to other transitive dependencies which require version >= 5.0.0.0.

Configuration

No response

Other information

From Procmon Logs, it's visible that if we are running the Windows Powershell directly, then it loads the assembly from this location - %SystemRoot%\System32\WindowsPowerShell\v1.0
But when we execute the script via my application, it loads from my application context.

Note: Only in Windows 11 24H2, the System.Security.Principal.Windows.dll (Version=4.1.1.0) is bundled with the system powershell in this location - %SystemRoot%\System32\WindowsPowerShell\v1.0\

Similar issues:

@dotnet-issue-labeler dotnet-issue-labeler bot added the needs-area-label An area label is needed to ensure this gets routed to the appropriate area owners label May 6, 2025
@dotnet-policy-service dotnet-policy-service bot added the untriaged New issue has not been triaged by the area owner label May 6, 2025
Copy link
Contributor

Tagging subscribers to this area: @dotnet/area-system-runtime
See info in area-owners.md if you want to be subscribed.

@vcsjones vcsjones removed the needs-area-label An area label is needed to ensure this gets routed to the appropriate area owners label May 6, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-System.Runtime untriaged New issue has not been triaged by the area owner
Projects
None yet
Development

No branches or pull requests

3 participants