我们可以确定这一点的一种方法是判断PSVersionInfo.PSVersion
Property的值,该方法需要反射,因为PSVersionInfo
类在Windows PowerShell5.1中没有公开.
using System;
using System.Management.Automation;
using System.Reflection;
namespace Testing;
internal static class PSVersion
{
private static bool? s_isCore;
// internal assuming we don't want to expose this
internal static bool IsCoreCLR => s_isCore ??= IsCore();
private static bool IsCore()
{
PropertyInfo property = typeof(PowerShell)
.Assembly.GetType("System.Management.Automation.PSVersionInfo")
.GetProperty(
"PSVersion",
BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
return (Version)property.GetValue(property) is not { Major: 5, Minor: 1 };
}
}
如果我们利用PSCmdlet
,另一种方法是通过cmdlet的SessionState
Property获取IsCoreCLR
的值:
using System.Management.Automation;
namespace Testing;
[Cmdlet(VerbsDiagnostic.Test, "PSVersion")]
public sealed class TestPSVersionCommand : PSCmdlet
{
private static bool? s_isCore;
private bool IsCoreCLR => s_isCore ??= IsCore();
protected override void EndProcessing()
{
if (IsCoreCLR)
{
// call 6+ method here
return;
}
// call 5.1 method here
}
private bool IsCore() =>
(bool?)SessionState.PSVariable.GetValue("IsCoreCLR") is true;
}