如何在 Powershell 中从 .net 框架调用重载的静态方法?

2024-03-23

以下是我尝试过的内容和发生的情况的记录。

我正在寻找如何调用特定重载以及解释为什么以下内容不起作用。如果您的答案是“您应该使用此命令行开关”或“调用两次”,请理解我不接受您的答案。

PS C:\> [System.IO.Path]::Combine("C:\", "foo")
C:\foo
PS C:\> [System.IO.Path]::Combine("C:\", "foo", "bar")
Cannot find an overload for "Combine" and the argument count: "3".
At line:1 char:26
+ [System.IO.Path]::Combine <<<< ("C:\", "foo", "bar")
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

PS C:\> [System.IO.Path]::Combine(, "C:\", "foo", "bar")
Missing ')' in method call.
At line:1 char:27
+ [System.IO.Path]::Combine( <<<< , "C:\", "foo", "bar")
    + CategoryInfo          : ParserError: (CloseParenToken:TokenId) [], Paren
   tContainsErrorRecordException
    + FullyQualifiedErrorId : MissingEndParenthesisInMethodCall

PS C:\> [System.IO.Path]::Combine($("C:\", "foo", "bar"))
Cannot find an overload for "Combine" and the argument count: "1".
At line:1 char:26
+ [System.IO.Path]::Combine <<<< ($("C:\", "foo", "bar"))
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

这就是我在 c# 中所做的,它有效:

var foobar = Path.Combine(@"C:\", "foo", "bar");
Console.WriteLine(foobar);

什么 Powershell 将调用该特定重载? Path.Combine 具有以下两者:

public static string Combine (string path1, string path2, string path3);
public static string Combine (params string[] paths);

是否可以同时调用这两个,或者只调用其中一个?显然,在这种具体情况下,很难区分其中的差异。


接受多个参数的路径重载仅在 .NET 4 及更高版本中可用。您需要创建一个配置文件来告诉 Powershell 使用 .NET 4 启动,这将使您能够访问这些方法。

在 $pshome 中创建一个名为“powershell.exe.config”的文件,其中包含以下内容:

<?xml version="1.0"?> 
<configuration> 
    <startup useLegacyV2RuntimeActivationPolicy="true"> 
        <supportedRuntime version="v4.0.30319"/> 
        <supportedRuntime version="v2.0.50727"/> 
    </startup> 
</configuration>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Powershell 中从 .net 框架调用重载的静态方法? 的相关文章

随机推荐