Runtimeexception: System.management.Automation.cmdletinVocationException: незаконные символы в пути. ---> System.argumenC#

Место общения программистов C#
Ответить
Anonymous
 Runtimeexception: System.management.Automation.cmdletinVocationException: незаконные символы в пути. ---> System.argumen

Сообщение Anonymous »

У меня есть сервис Windows, которая работает, как и ожидалось. Он запускает сценарий PowerShell на машине. Он работал нормально до 3 дней, но не начало выдавать экстремение времени выполнения на машине Windows 11. Его провал (придает исключение на mypipeline.invoke () ) только на нескольких выбранных машинах Windows 11, но работает, как и ожидалось, на многих машинах Windows 11. Его провалится с любым простым сценарием. Но я увидел на машине, на которой его сбой этого DLL не присутствует, так же как путь System.Management.Automation.DLL недавно изменяется? Runtimeexception: System.management.Automation.cmdletinVocationException: незаконные символы в пути. ---> 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..cor (путь String, режим FileMode, FileCcess, FileShare Share, Int32 Buffersize, FileOption Boolean Checkhost)
at System.io.StreamReader..Cor (String Path, кодирование кодирования, Boolean DecectencodingFromByteRoderMarks, Int32 Buffersize, Boolean Checkhost)
at System.io.file.InternalReadLext (Путь строки, энкодирование, бодвое проверка)
Microsoft.powershell.commands.addtypecommandbase.populatesource ()
at microsoft.powershell.commands.addtypecommand.endprocessing ()
at system.management. System.Management.Automation.Runspaces.PipelineBase.invoke (Ienumerable Input)
at atger.tasks.taskimpl.advanced.powershelltask. C__displayclass43_3.b__3 () C: \ work \ uno-automation \ src_.net \ projects \ Agent \ Agent.TaskCatalog \ TaskImpl \ Advanced \ powerShelltask.cs: строка 764
at atagt.core.utils.time.stopwatchextensions.tracetimeOf [t] (String TraceInfonam Agent.tasks.taskimpl.advanced.powershelltask.run (runconfig config, cancellationtoken aborttoken) в C: \ work \ uno-automation \ src_.net \ projects \ Agent.taskcatalog \ taskimpl \ Advanced \ PowerShellTasprivate 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;
}
}


Подробнее здесь: https://stackoverflow.com/questions/797 ... ion-illega
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»