Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
47 commits
Select commit Hold shift + click to select a range
944cc45
Add issue 2205 regression test
Copilot Aug 19, 2026
d7d278c
Correct issue 2205 regression assertion
Copilot Aug 19, 2026
b8e7410
Add recursive issue 2205 regression scenario
Copilot Aug 19, 2026
3d791b2
Isolate issue 2205 regression fixture
Copilot Aug 19, 2026
3326269
Add issue 2205 failure regression
Copilot Aug 19, 2026
c51a892
Isolate issue 2205 failing regression
Copilot Aug 19, 2026
39b5356
Do not fail analysis on transient command lookup failures (issue 2205)
Copilot Aug 19, 2026
bc604c9
Address code review: evict only the faulted cache entry, clarify test…
Copilot Aug 19, 2026
9734b62
Merge pull request #1 from jessehouwing/copilot/create-unit-test-for-…
jessehouwing Aug 19, 2026
476e1a3
Serialize command info lookups on a single dedicated runspace
Copilot Aug 19, 2026
c4321d8
Make concurrency test safe against Helper singleton initialization order
Copilot Aug 19, 2026
ae52d7c
Address review: take the runspace lock on both dispose paths
Copilot Aug 19, 2026
469fd0a
Merge pull request #2 from jessehouwing/copilot/marshal-concurrent-ca…
jessehouwing Aug 19, 2026
8a75d6f
Merge branch 'PowerShell:main' into main
jessehouwing Sep 14, 2026
af4cb17
Add isolated cold and warm ScriptAnalyzer benchmark workflow
Copilot Sep 14, 2026
acd3f00
Expand performance comparison to Linux and semver repository workload
Copilot Sep 14, 2026
7a233e4
Preserve full PowerShell source tree in performance benchmarks
Copilot Sep 14, 2026
ac6dab8
Pin download-artifact to patched v4.3.0 commit
Copilot Sep 14, 2026
d82000d
Merge pull request #4 from jessehouwing/copilot/add-workflow-dispatch…
jessehouwing Sep 14, 2026
ada251b
Initial plan
Copilot Sep 14, 2026
36f9aef
Harden command lookup against Get-Command resolution failures
Copilot Sep 14, 2026
b13bae1
Avoid runspace races when resolving exported function parameters
Copilot Sep 14, 2026
e1ea2fb
Merge pull request #5 from jessehouwing/copilot/fix-benchmark-upstrea…
jessehouwing Sep 14, 2026
936b71f
Merge remote-tracking branch 'origin/main' into copilot/fix-benchmark…
Copilot Sep 14, 2026
1a928b6
Serialize command metadata reads with runspace command lookups
Copilot Sep 14, 2026
9ac604a
Merge pull request #7 from jessehouwing/copilot/fix-benchmark-fork-se…
jessehouwing Sep 14, 2026
b3d23b2
Record three-way benchmark requirement
Copilot Sep 14, 2026
ffdfa6f
Merge branch 'main' into main
bergmeister Sep 14, 2026
4125239
Merge branch 'main' into main
bergmeister Sep 14, 2026
37e07fd
Optimize synchronized metadata and add three-way performance benchmarks
Copilot Sep 14, 2026
aacafd8
Disable telemetry collection in performance comparisons
Copilot Sep 14, 2026
8cfecbf
Add consolidated performance matrix summary job
Copilot Sep 14, 2026
7b22321
Merge pull request #9 from jessehouwing/copilot/perf-additional-metri…
jessehouwing Sep 14, 2026
0d11274
Make PowerShell engine retries selectable and observable
Copilot Sep 14, 2026
028c67c
Fix spurious retries for unknown commands and verify retry modes
Copilot Sep 14, 2026
078fc8b
Centralize command metadata recovery and remove rule-level catches
Copilot Sep 14, 2026
7976235
Preserve negative caching while evicting exhausted lookup failures
Copilot Sep 14, 2026
c440009
Merge pull request #10 from jessehouwing/copilot/add-if-else-statements
jessehouwing Sep 14, 2026
1b37795
Update perf workflow for retry ifdef variants
Copilot Sep 14, 2026
95c089c
Merge pull request #11 from jessehouwing/copilot/add-perf-workflow-retry
jessehouwing Sep 14, 2026
ecebce4
Merge branch 'PowerShell:main' into main
jessehouwing Sep 14, 2026
f819022
Restore full benchmark matrix and distinct retry build variants
Copilot Sep 14, 2026
beeb3f9
Merge pull request #12 from jessehouwing/copilot/add-benchmark-compar…
jessehouwing Sep 14, 2026
c8e59b0
Remove engine retries and performance telemetry
jessehouwing Sep 14, 2026
d5e87f6
Remove perf branch from performance benchmark
jessehouwing Sep 14, 2026
7d4a11f
Merge pull request #13 from jessehouwing/perf
jessehouwing Sep 14, 2026
b8472db
Use C# 5 compatible syntax in Add-Type test fixtures
jessehouwing Sep 15, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
436 changes: 436 additions & 0 deletions .github/workflows/performance.yml

Large diffs are not rendered by default.

304 changes: 278 additions & 26 deletions Engine/CommandInfoCache.cs

Large diffs are not rendered by default.

24 changes: 24 additions & 0 deletions Engine/CommandParameterSnapshot.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System.Collections.ObjectModel;
using System.Linq;
using System.Management.Automation;

namespace Microsoft.Windows.PowerShell.ScriptAnalyzer
{
/// <summary>Detached parameter facts, safe to consume without driving a PowerShell runspace.</summary>
public sealed class CommandParameterSnapshot
{
public string Name { get; }
public bool SwitchParameter { get; }
public ReadOnlyCollection<string> Aliases { get; }

internal CommandParameterSnapshot(ParameterMetadata parameter)
{
Name = parameter.Name;
SwitchParameter = parameter.SwitchParameter;
Aliases = new ReadOnlyCollection<string>(parameter.Aliases.ToArray());
}
}
}
74 changes: 65 additions & 9 deletions Engine/Helper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,15 @@ public PSModuleInfo GetModuleManifest(string filePath, out IEnumerable<ErrorReco
return psModuleInfo;
}

/// <summary>Shares validation between built-in rules during one syntax-tree analysis only.</summary>
public PSModuleInfo GetModuleManifestForAnalysis(string filePath, out IEnumerable<ErrorRecord> errorRecords)
{
var cache = ModuleManifestAnalysisCache.Current;
return cache == null
? GetModuleManifest(filePath, out errorRecords)
: cache.Get(this, filePath, out errorRecords);
}

/// <summary>
/// Checks if the error record is MissingMemberException
/// </summary>
Expand Down Expand Up @@ -399,18 +408,22 @@ public HashSet<string> GetExportedFunction(Ast ast)
List<string> exportFunctionsCmdlet = Helper.Instance.CmdletNameAndAliases("export-modulemember");

// find functions exported
IEnumerable<Ast> cmdAsts = ast.FindAll(item => item is CommandAst
&& exportFunctionsCmdlet.Contains((item as CommandAst).GetCommandName(), StringComparer.OrdinalIgnoreCase), true);

CommandInfo exportMM = Helper.Instance.GetCommandInfo("export-modulemember", CommandTypes.Cmdlet);

// switch parameters
IEnumerable<ParameterMetadata> switchParams = (exportMM != null) ? exportMM.Parameters.Values.Where<ParameterMetadata>(pm => pm.SwitchParameter) : Enumerable.Empty<ParameterMetadata>();
var cmdAsts = ast.FindAll(item => item is CommandAst
&& exportFunctionsCmdlet.Contains((item as CommandAst).GetCommandName(), StringComparer.OrdinalIgnoreCase), true).ToArray();
if (cmdAsts.Length == 0)
{
return exportedFunctions;
}

if (exportMM == null)
// Export-ModuleMember has no dynamic parameters. Resolve names from its static
// metadata instead of ResolveParameter(), which re-enters the cached command's
// runspace and races with command lookups and metadata queries on other rule threads.
var parameters = GetCommandParameterSnapshot("export-modulemember", CommandTypes.Cmdlet);
if (parameters == null)
{
return exportedFunctions;
}
var switchParams = parameters.Values.Where(pm => pm.SwitchParameter);

foreach (CommandAst cmdAst in cmdAsts)
{
Expand All @@ -429,7 +442,20 @@ public HashSet<string> GetExportedFunction(Ast ast)
if (ceAst is CommandParameterAst)
{
var paramAst = ceAst as CommandParameterAst;
var param = exportMM.ResolveParameter(paramAst.ParameterName);
CommandParameterSnapshot param;
if (!parameters.TryGetValue(paramAst.ParameterName, out param))
{
param = parameters.Values.FirstOrDefault(pm =>
pm.Aliases.Contains(paramAst.ParameterName, StringComparer.OrdinalIgnoreCase));
if (param == null)
{
var matches = parameters.Values.Where(pm =>
pm.Name.StartsWith(paramAst.ParameterName, StringComparison.OrdinalIgnoreCase)
|| pm.Aliases.Any(alias => alias.StartsWith(paramAst.ParameterName, StringComparison.OrdinalIgnoreCase)))
.Take(2).ToArray();
param = matches.Length == 1 ? matches[0] : null;
}
}

if (param == null)
{
Expand Down Expand Up @@ -671,6 +697,36 @@ public CommandInfo GetCommandInfo(string name, CommandTypes? commandType = null,
return CommandInfoCache.GetCommandInfo(name, commandTypes: commandType, bypassCache: bypassCache);
}

/// <summary>
/// Retrieves command parameters with centralized recovery; returns null when metadata is unavailable.
/// </summary>
public Dictionary<string, ParameterMetadata> GetCommandParameters(
string name, CommandTypes? commandType = null, bool bypassCache = false)
{
return CommandInfoCache.GetCommandParameters(name, commandType, bypassCache);
}

/// <summary>
/// Retrieves command parameter sets with centralized recovery; returns null when metadata is unavailable.
/// </summary>
public ReadOnlyCollection<CommandParameterSetInfo> GetCommandParameterSets(string name)
{
return CommandInfoCache.GetCommandParameterSets(name);
}

/// <summary>Gets detached parameter facts or null when unavailable; only static cmdlet metadata is cached.</summary>
public IReadOnlyDictionary<string, CommandParameterSnapshot> GetCommandParameterSnapshot(
string name, CommandTypes? commandType = null, bool bypassCache = false)
{
return CommandInfoCache.GetParameterSnapshot(name, commandType, bypassCache);
}

/// <summary>Gets the mandatory parameter summary under a single runspace lock, or null when unavailable.</summary>
public IReadOnlyList<string> GetMandatoryParameterNames(string name)
{
return CommandInfoCache.GetMandatoryParameterNames(name);
}

/// <summary>
/// Returns the get, set and test targetresource dsc function
/// </summary>
Expand Down
55 changes: 55 additions & 0 deletions Engine/ModuleManifestAnalysisCache.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Management.Automation;

namespace Microsoft.Windows.PowerShell.ScriptAnalyzer
{
// Owned by one AnalyzeSyntaxTree call and explicitly installed on its rule workers.
// It cannot outlive that analysis or affect unrelated public GetModuleManifest callers.
internal sealed class ModuleManifestAnalysisCache
{
[ThreadStatic]
internal static ModuleManifestAnalysisCache Current;

private readonly Dictionary<string, Result> results = new Dictionary<string, Result>(StringComparer.Ordinal);

internal PSModuleInfo Get(Helper helper, string path, out IEnumerable<ErrorRecord> errors)
{
lock (results)
{
if (!results.TryGetValue(path, out var result))
{
var module = helper.GetModuleManifest(path, out var moduleErrors);
result = new Result { Module = module, Errors = moduleErrors };
results.Add(path, result);
}
errors = result.Errors;
return result.Module;
}
}

internal Scope Enter() => new Scope(this);

internal struct Scope : IDisposable
{
private readonly ModuleManifestAnalysisCache previous;

internal Scope(ModuleManifestAnalysisCache cache)
{
previous = Current;
Current = cache;
}

public void Dispose() => Current = previous;
}

private sealed class Result
{
internal PSModuleInfo Module;
internal IEnumerable<ErrorRecord> Errors;
}
}
}
2 changes: 2 additions & 0 deletions Engine/ScriptAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2128,6 +2128,7 @@ public IEnumerable<DiagnosticRecord> AnalyzeSyntaxTree(
string fileName = filePathIsNullOrWhiteSpace ? String.Empty : System.IO.Path.GetFileName(filePath);
if (this.ScriptRules != null)
{
var manifestCache = new ModuleManifestAnalysisCache();
var allowedRules = this.ScriptRules.Where(IsRuleAllowed);
if (allowedRules.Any())
{
Expand All @@ -2139,6 +2140,7 @@ public IEnumerable<DiagnosticRecord> AnalyzeSyntaxTree(

// Ensure that any unhandled errors from Rules are converted to non-terminating errors
// We want the Engine to continue functioning even if one or more Rules throws an exception
using (manifestCache.Enter())
try
{
if (helpRule && helpFile)
Expand Down
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,12 @@ To install **PSScriptAnalyzer** from source code:
Import-Module .\out\PSScriptAnalyzer\[version]\PSScriptAnalyzer.psd1
```

- Command metadata handling lives in `CommandInfoCache`, not individual rules. Its parameter,
parameter-set and snapshot APIs return null when PowerShell metadata is unavailable, while
unexpected exceptions still propagate. Failed lookups and command objects with failed
metadata are evicted so subsequent calls can recover; genuine missing commands retain
negative caching.

To confirm installation: run `Get-ScriptAnalyzerRule` in the PowerShell console to obtain the
built-in rules.

Expand Down
2 changes: 1 addition & 1 deletion Rules/MissingModuleManifestField.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
if (Helper.IsModuleManifest(fileName))
{
IEnumerable<ErrorRecord> errorRecords;
var psModuleInfo = Helper.Instance.GetModuleManifest(fileName, out errorRecords);
var psModuleInfo = Helper.Instance.GetModuleManifestForAnalysis(fileName, out errorRecords);
if (errorRecords != null)
{
foreach (var errorRecord in errorRecords)
Expand Down
43 changes: 4 additions & 39 deletions Rules/UseCmdletCorrectly.cs
Original file line number Diff line number Diff line change
Expand Up @@ -145,41 +145,9 @@ private bool MandatoryParameterExists(CommandAst cmdAst)

// Gets mandatory parameters from cmdlet.
// If cannot find any mandatory parameter, it's not necessary to do a further check for current cmdlet.
var mandatoryParameters = new List<ParameterMetadata>();
try
{
int noOfParamSets = cmdInfo.ParameterSets.Count;
foreach (ParameterMetadata pm in cmdInfo.Parameters.Values)
{
int count = 0;

if (pm.Attributes.Count < noOfParamSets)
{
continue;
}
var mandatoryParameters = Helper.Instance.GetMandatoryParameterNames(cmdAst.GetCommandName());

foreach (Attribute attr in pm.Attributes)
{
if (!(attr is ParameterAttribute)) continue;
if (((ParameterAttribute)attr).Mandatory)
{
count += 1;
}
}

if (count >= noOfParamSets)
{
mandatoryParameters.Add(pm);
}
}
}
catch (Exception)
{
// For cases like cmd.exe. Also for runtime exception
return true;
}

if (mandatoryParameters.Count == 0)
if (mandatoryParameters == null || mandatoryParameters.Count == 0)
{
return true;
}
Expand All @@ -188,8 +156,8 @@ private bool MandatoryParameterExists(CommandAst cmdAst)
foreach (CommandElementAst commandElementAst in cmdAst.CommandElements.OfType<CommandParameterAst>())
{
CommandParameterAst cpAst = (CommandParameterAst)commandElementAst;
if (mandatoryParameters.Count<ParameterMetadata>(item =>
item.Name.Equals(cpAst.ParameterName, StringComparison.OrdinalIgnoreCase)) > 0)
if (mandatoryParameters.Any(item =>
item.Equals(cpAst.ParameterName, StringComparison.OrdinalIgnoreCase)))
{
return true;
}
Expand Down Expand Up @@ -254,6 +222,3 @@ public string GetSourceName()
}
}




20 changes: 9 additions & 11 deletions Rules/UseCorrectCasing.cs
Original file line number Diff line number Diff line change
Expand Up @@ -119,24 +119,22 @@ public override IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string file
}

var commandParameterAsts = commandAst.FindAll(
testAst => testAst is CommandParameterAst, true).Cast<CommandParameterAst>();
Dictionary<string, ParameterMetadata> availableParameters;
try
testAst => testAst is CommandParameterAst, true).Cast<CommandParameterAst>().ToArray();
if (commandParameterAsts.Length == 0)
{
availableParameters = commandInfo.Parameters;
continue;
}
// It's a known issue that objects from PowerShell can have a runspace affinity,
// therefore if that happens, we query a fresh object instead of using the cache.
// https://github.com/PowerShell/PowerShell/issues/4003
catch (InvalidOperationException)
var availableParameters = Helper.Instance.GetCommandParameterSnapshot(commandName);
if (availableParameters is null)
{
commandInfo = Helper.Instance.GetCommandInfo(commandName, bypassCache: true);
availableParameters = commandInfo.Parameters;
// The parameters of this command cannot be determined reliably,
// so skip the parameter casing check instead of failing the analysis.
continue;
}
foreach (var commandParameterAst in commandParameterAsts)
{
var parameterName = commandParameterAst.ParameterName;
if (availableParameters.TryGetValue(parameterName, out ParameterMetadata parameterMetaData))
if (availableParameters.TryGetValue(parameterName, out CommandParameterSnapshot parameterMetaData))
{
var correctlyCasedParameterName = parameterMetaData.Name;
if (!parameterName.Equals(correctlyCasedParameterName, StringComparison.Ordinal))
Expand Down
2 changes: 1 addition & 1 deletion Rules/UseToExportFieldsInManifest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)

// check if valid module manifest
IEnumerable<ErrorRecord> errorRecord = null;
PSModuleInfo psModuleInfo = Helper.Instance.GetModuleManifest(fileName, out errorRecord);
PSModuleInfo psModuleInfo = Helper.Instance.GetModuleManifestForAnalysis(fileName, out errorRecord);
if ((errorRecord != null && errorRecord.Count() > 0) || psModuleInfo == null)
{
yield break;
Expand Down
Loading