如何在.ps1文件

时间:2017-07-04 13:50:41

标签: c# powershell powershell-v4.0

以下C#片段嵌入在powershell(.ps1)文件中,并生成System.Management.Automation.RuntimeException。删除"字符串s"而且例外消失了。试图使用大写"字符串"并尝试添加名称空间" System.String"和其他各种方法,但仍然得到例外。这让我疯了,请帮助我理解为什么会这样。

$code = @"
public static class foo
{
  public static bool check()
  {
    string s;
    return false;
  }
}

代码就像这样调用;

try
{
  Add-Type -TypeDefinition $code -Language CSharp
}
catch{} // ignore TYPE_ALREADY_EXISTS exception
$res = [foo]::check();

以下是例外情况;

Exception: System.Management.Automation.RuntimeException: unable to find type [foo].
TargetObject: foo
CategoryInfo: InvalidOperation (foo:Typename) [], RuntimeException
FullyQualifiedErrorId: TypeNotFound
InvocationInfo: System.Management.Automation.InvocationInfo

1 个答案:

答案 0 :(得分:0)

$code = @"
public static class foo {
  public static bool check() {
    string s;
    return false;
  }
}
"@

Add-Type -TypeDefinition $code -Language CSharp

产生

  

警告为错误:声明变量's'但从未使用

它不允许您声明未使用的变量。