Описание < /h3>
У меня есть таргетинг приложения для .NET 4.7.2 Framework. Существует код для запуска данного сценария PowerShell, он работает, как и ожидалось. Но только на машине операционной системы Windows 11 24H2 конкретный сценарий get-appxpackage , он не удается за исключением ниже. Другие сценарии PowerShell работают, как и ожидалось в этой версии OS.
Существует System.security.principal.Windows DLL 5.0.0 Версия DLL Установленного пути. < /P>
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);
< /code>
get-appxpackage: не может загрузить файл или сборку 'System.security.principal.windows, версия = 4.1.1.0, культура = нейтральная, publickeytoken = b03f5f7f11d50a3a' или одна из ее зависимости. Определенное определение расположенного сборки не соответствует ссылке на сборку. (Исключение из HRESULT: 0x80131040)
at line: 1 char: 1
get-appxpackage < /p>
< /code>
< /li>
< /ul>
CategoryInfo: notppucified: (:) [get-appxpackage], fileloadexception
полностью квалифицированноррид: system.io.fileloadexcept /> < /blockquote>
Шаги воспроизведения < /h3>
Иметь машину Windows 11 24H2. < /p>
Запустите заданный код. < /p>
ожидаемое поведение < /h3>
. Исключение времени выполнения.
Подробнее здесь: https://stackoverflow.com/questions/794 ... ersion-4-1