c# - Could not load file or assembly 'System.Security.Principal.Windows, Version=4.1.1.0 - Stack Overflow

DescriptionI have an application targeting .NET 4.7.2. There is a code to run the given PowerShell scr

Description

I have an application targeting .NET 4.7.2. There is a code to run the given PowerShell script it is working as expected. but only on the Windows 11 24H2 operating system machine the particular script Get-AppxPackage, it is failing with the below exception. Other PowerShell scripts are running as expected on this version of OS.

There is a System.Security.Principal.Windows dll of version 5.0.0 in the installed path.

private RunOutput Run(RunConfig config, CancellationToken abortToken)
{
    var common = new PowerShellCommonHelpers();
    // ReSharper disable ConvertToUsingDeclaration
    using (var eFs = new FileStream(config.ErrorFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
    using (var errorWriter = new StreamWriter(eFs, new UTF8Encoding(false)))
    using (var oFs = new FileStream(config.OutputFilePath, FileMode.Create, FileAccess.Write, FileShare.None))

    using (var outputWriter = new StreamWriter(oFs, new UTF8Encoding(false)) { AutoFlush = false })
    {
        var runOutput = new RunOutput();

        var strPrevousExecutionPolicy = string.Empty;
        var ysnOk = true;

        if (config.OverrideExecutionPolicy)
        {
            //Check if PowerShell GPO is active; do NOT set execution policy if GPO is active because it will fail!
            if (PowerShellCommon.fysnPowerShellGpoActive())
                config.OverrideExecutionPolicy = false;
            //To prevent reset to original execution policy later on
            else
                ysnOk = PowerShellCommon.fysnSetExecutionPolicy("Unrestricted", ref strPrevousExecutionPolicy);
        }

        if (ysnOk)
        {
            // ReSharper disable once UnusedVariable USED FOR DEBUGGING
            const string resourceText = "";
            var scriptToRun = string.IsNullOrEmpty(resourceText)
                ? config.Source
                : File.ReadAllText(resourceText);

            var myRunSpaceConfiguration = TryLoadConsoleFile(config, errorWriter, outputWriter);

            var myRespsHost = new RESStreamingPSHost();
            myRespsHost.ProgressMessage += MyRespsHostOnProgressMessage;
            // ReSharper disable once AccessToDisposedClosure lambda is in scope.
            myRespsHost.OnOutput += value => outputWriter.Write(value);
            // ReSharper disable once AccessToDisposedClosure lambda is in scope.
            myRespsHost.OnError += value => errorWriter.Write(value);


            if (config.OutputWidth == 0) config.OutputWidth = 16386;

            RESDiagnostics.TraceInfo("Changing output buffer width to {0}.", config.OutputWidth);
            myRespsHost.BufferSize = new Size(config.OutputWidth, 1000);

            Runspace myRunSpace;

            if (myRunSpaceConfiguration != null)
            {
                myRunSpace = RunspaceFactory.CreateRunspace(myRespsHost, myRunSpaceConfiguration);
                RESDiagnostics.TraceInfo("Done loading with settings.");
            }
            else
            {
                myRunSpace = RunspaceFactory.CreateRunspace(myRespsHost);
                RESDiagnostics.TraceInfo("Done loading without settings.");
            }

            myRunSpace.Open();
            
            var myPipeLine = CreatePipeline(myRunSpace, scriptToRun, config.Mappings);

            try
            {
                var abortCheckerTokenSource = new CancellationTokenSource();
                Task.Factory.StartNew(
                    (abortChecker) =>
                    {
                        while (!abortToken.IsCancellationRequested && !abortCheckerTokenSource.Token.IsCancellationRequested)
                        {
                            Thread.Sleep(200);
                        }

                        if (abortToken.IsCancellationRequested)
                        {
                            myRunSpace.Close();
                            myPipeLine.Stop();
                        }
                    }, abortCheckerTokenSource.Token);

                var myResults =
                    StopwatchExtensions.TraceTimeOf("Running script.", () => myPipeLine.Invoke());

                // Invoke() finished => finish abort checker thread
                abortCheckerTokenSource.Cancel();
                abortCheckerTokenSource.Dispose();

                if (abortToken.IsCancellationRequested)
                {
                    myRunSpace.Close();
                    return runOutput;
                }

                StopwatchExtensions.TraceTimeOf($"Output messages {myResults.Count}", outputStream =>
                {
                    foreach (var myPsObjectLoopVariable in myResults)
                    {
                        if (abortToken.IsCancellationRequested)
                        {
                            myRunSpace.Close();
                            return;
                        }

                        var myPsObject = myPsObjectLoopVariable;
                        if (myPsObject.BaseObject is ErrorRecord record)
                        {
                            outputStream.Write(record.ToString());
                            outputStream.WriteLine(record.InvocationInfo.PositionMessage);
                        }
                        else
                        {
                            outputStream.WriteLine(myPsObject.ToString());
                        }
                    }
                }, outputWriter);

                if (abortToken.IsCancellationRequested)
                {
                    return runOutput;
                }

                StopwatchExtensions.TraceTimeOf("Messages on the error pipeline", errorStream =>
                {
                    while (!myPipeLine.Error.EndOfPipeline)
                    {
                        if (abortToken.IsCancellationRequested)
                        {
                            myRunSpace.Close();
                            return;
                        }

                        var myPsObject = (PSObject)myPipeLine.Error.Read();
                        if (myPsObject.BaseObject is ErrorRecord record)
                        {
                            errorStream.Write(record.ToString());
                            errorStream.WriteLine(record.InvocationInfo.PositionMessage);
                        }
                        else
                        {
                            errorStream.WriteLine(myPsObject.ToString());
                        }
                    }
                }, errorWriter);

                if (abortToken.IsCancellationRequested)
                {
                    myRunSpace.Close();
                    return runOutput;
                }

                runOutput.ExitCode = myRespsHost.ExitCode;

                if (SidekickState.Instance.AgentIPC != null)
                {
                    StopwatchExtensions.TraceTimeOf("Extract Variables To Parameters", () =>
                    {
                        common.ExtractVariablesToParameters(myRunSpace, scriptToRun, OutputMaxSize, out _wasParameterTrimmed);
                    });

                    StopwatchExtensions.TraceTimeOf("Blob Override", () =>
                    {
                        var automationfabricbloboverride = common.GlobalParameterValue(
                            myRunSpace.SessionStateProxy.PSVariable,
                            "automationfabricbloboverride",
                            scriptToRun
                        );
                        if (automationfabricbloboverride == null) return;

                        _blobOverride = automationfabricbloboverride.ToString();
                        RESDiagnostics.TraceInfo($"blob overriden with length: {_blobOverride.Length}");
                    });
                }
            }
            catch (RuntimeException ex)
            {
                RESDiagnostics.TraceError($"A runtime exception occured");

                errorWriter.Write(ex.Message);

                if (ex.ErrorRecord.InvocationInfo != null)
                    errorWriter.WriteLine(ex.ErrorRecord.InvocationInfo.PositionMessage);
            }
            catch (Exception ex)
            {
                RESDiagnostics.TraceError("A general exception occured.");

                errorWriter.Write(ex.Message);
            }


            RESDiagnostics.TraceInfo("Result code");
            var resultCodeValue = common.GlobalParameterValue(
                myRunSpace.SessionStateProxy.PSVariable,
                "resultcodeinternalapivalue",
                scriptToRun
            );


            if (resultCodeValue != null && int.TryParse(resultCodeValue.ToString(), out var resCode))
                runOutput.ResCode = resCode;

            try
            {
                RESDiagnostics.TraceInfo("Preparing to extract the extra log");

                var extraLog = common.GlobalParameterValue(
                    myRunSpace.SessionStateProxy.PSVariable,
                    "internalenginelogerrordetails",
                    scriptToRun
                )?.ToString();
                if (!string.IsNullOrEmpty(extraLog))
                {
                    RESDiagnostics.TraceError(extraLog);
                }
                else
                {
                    RESDiagnostics.TraceInfo("Extra log not found");
                }
            }
            catch (Exception e)
            {
                RESDiagnostics.TraceInfo($"Extra log exception {e.Message}, {e.StackTrace}");
            }




            myRunSpace.Close();

            if (!config.OverrideExecutionPolicy) return runOutput;

            RESDiagnostics.TraceInfo("Revert execution policy");
            string dummy = null;
            PowerShellCommon.fysnSetExecutionPolicy(strPrevousExecutionPolicy, ref dummy);
        }
        else
        {
            errorWriter.Write("Unable to set execution policy.");
        }

        return runOutput;
    }
}

runOutput = Run(new RunConfig
{
    OutputWidth = 500,
    OverrideExecutionPolicy = false
    PsConsoleFilename = null,
    Source = Get-AppxPackage,
    ErrorFilePath = "C:\WINDOWS\SystemTemp\tmpFFFF.tmp",
    OutputFilePath = "C:\WINDOWS\SystemTemp\tmp1.tmp",
    Mappings = {},
}, cancellationToken);

Get-AppxPackage : 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)
At line:1 char:1
Get-AppxPackage

CategoryInfo : NotSpecified: (:) [Get-AppxPackage], FileLoadException
FullyQualifiedErrorId : System.IO.FileLoadException,Microsoft.Windows.Appx.PackageManager.Commands.GetAppxPackageCommand

Reproduction steps

  • Have the Windows 11 24H2 machine.
  • Run the given code.

Expected behavior

It should run the given script

Actual behavior

It throws a runtime exception.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744813784a4595203.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信