从PowerShell中,我们可以使用$PSVersionTable automatic variable轻松判断呼叫者使用的是Windows PowerShell 5.1还是更新版本:

$PSVersion = $PSVersionTable.PSVersion
if ($PSVersion.Major -eq 5 -and $PSVersion.Minor -eq 1) {
    # do 5.1 stuff here
    return
}

# do 6+ stuff here

或者我们甚至可以使用$IsCoreCLR:

if ($IsCoreCLR) {
    # do 6+ stuff here
    return
}

# do 5.1 stuff here

如果目标是netstandard2.0,我们如何在C#中做到同样的事情呢?

推荐答案

我们可以确定这一点的一种方法是判断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;
}

Csharp相关问答推荐

声明和实例化时抽象类和Generics的结合问题

在实际上是List T的 IESEARCH上多次调用First()是否不好?

在ASP.NET中为数据注释 Select 合适的语言

ListaryImportProperty的默认DllImportSearchPathsProperty行为

总是丢弃返回的任务和使方法puc无效之间有区别吗?

Entity Framework Core 8 dbcontext—无法以多对多关系添加某些行'

Unity 2D自顶向下弓旋转

ASP.NET Core 8.0 JWT验证问题:尽管令牌有效,但SecurityTokenNoExpirationError异常

Int和uint相乘得到LONG?

如何使用新的Microsoft.IdentityModel.JsonWebToken创建JwtSecurityToken?

使用HttpResponseMessage中的嵌套列表初始化JSON

如何在实体框架中添加包含列表?

StackExchange.Redis.RedisServerException:调用ITransaction.ExecuteAsync()时出现错误未知命令取消监视

如何将此方法参数化并使其更灵活?

UWP应用程序try 将打包的本机.exe文件加载为C#程序集

使用带有参数和曲面的注入失败(&Q;)

在implementationFactory中避免循环依赖

如何在.NET Maui中将事件与MVVM一起使用?

如何在microsoft.clearscript.v8的jsondata中使用Linq

JSON串行化程序问题.SQLite中的空值