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

Skip to content

RuntimeException: System.Management.Automation.CmdletInvocationException: Illegal characters in path. ---> System.ArgumentException: #26043

@viveknuna

Description

@viveknuna

Prerequisites

Steps to reproduce

Description

I have a windows service which is running as expected. It runs a powershell script on the machine. It was working fine before 3 days, but not it has started giving the runtime excption on windows 11 machine. Its failing (giving exception on myPipeLine.Invoke() ) only on few selected windows 11 machines but working as expected on many windows 11 machines. Its failing with any simple script. my target framework is 4.7.2.

When I checked on the machine on which its working that has the System.Management.Automation.dll on the path C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35. But I saw on machine on which its failing this dll is not present, so is the path of System.Management.Automation.dll changed recently?

Is it caused by recent windows release?

025-09-12 12:50:01.1250|INFO|sidekickLog| RuntimeException: System.Management.Automation.CmdletInvocationException: Illegal characters in path. ---> System.ArgumentException: Illegal characters in path. at System.Security.Permissions.FileIOPermission.EmulateFileIOPermissionChecks(String fullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean checkHost) at System.IO.File.InternalReadAllText(String path, Encoding encoding, Boolean checkHost) at Microsoft.PowerShell.Commands.AddTypeCommandBase.PopulateSource() at Microsoft.PowerShell.Commands.AddTypeCommand.EndProcessing() at System.Management.Automation.CommandProcessorBase.Complete() End of inner exception stack trace --- at System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable input) at Agent.Tasks.TaskImpl.Advanced.PowerShellTask.<>c__DisplayClass43_3.b__3() in C:\work\uno-Automation\src_.Net\Projects\Agent\Agent.TaskCatalog\TaskImpl\Advanced\PowerShellTask.cs:line 764 at Agent.Core.Utils.Time.StopwatchExtensions.TraceTimeOf[T](String traceInfoName, Func`1 func) at Agent.Tasks.TaskImpl.Advanced.PowerShellTask.Run(RunConfig config, CancellationToken abortToken) in C:\work\uno-Automation\src_.Net\Projects\Agent\Agent.TaskCatalog\TaskImpl\Advanced\PowerShellTask.cs:line 763

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);

            RESDiagnostics.TraceInfo($"Running script.{scriptToRun}");
            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());

                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.TraceInfo($" RuntimeException: {ex.ToString()}");
                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.TraceInfo($" Exception: {ex.ToString()}");
                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;
    }
}

Expected behavior

it should run as expected

Actual behavior

its gives the above mentioned exception

Error details

Environment data

Name                           Value
----                           -----
PSVersion                      5.1.26100.6584
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.26100.6584
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

Visuals

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs-TriageThe issue is new and needs to be triaged by a work group.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions