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

fcr*_*ick 4 powershell overloading

以下是我尝试过的内容和发生的事情的成绩单.

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

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
Run Code Online (Sandbox Code Playgroud)

这就是我在c#中所做的工作:

var foobar = Path.Combine(@"C:\", "foo", "bar");
Console.WriteLine(foobar);
Run Code Online (Sandbox Code Playgroud)

Powershell将调用特定的过载?Path.Combine具有以下两个:

public static string Combine (string path1, string path2, string path3);
public static string Combine (params string[] paths);
Run Code Online (Sandbox Code Playgroud)

是否可以调用这两个,或只调用一个?显然,在这种特殊情况下,很难区分它们.

Mik*_*keP 7

接受多个参数的Path重载只能在.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>
Run Code Online (Sandbox Code Playgroud)

  • 或者您可以安装和使用已在.NET 4.0上运行的powershell 3.0. (2认同)