【问题标题】:Why can I not cast to [PSSession] declaring function parameters?为什么我不能强制转换为 [PSSession] 声明函数参数?
【发布时间】:2016-09-30 17:11:55
【问题描述】:

我无法弄清楚如何正确转换 PSSession 以用作函数中的参数。

我是否必须加载程序集或其他东西?我正在使用 Powershell v4。

我喜欢转换我的函数参数以确保正确使用。我正在尝试的是:

function Some-Remote-Task([PSSession] $Session, [String]$Target) {
  # Do stuff...
}

但我在转换参数时收到此错误:

Unable to find type [PSSession]. Make sure that the assembly that contains this type is loaded.

此外,在有效会话中使用 $mySession.GetType() 会产生以下结果:

IsPublic IsSerial Name                                     BaseType                                                                                                                           
-------- -------- ----                                     --------                                                                                                                           
True     False    PSSession                                System.Object    

所以看起来这应该是正确的类型名称......

感谢所有帮助。

【问题讨论】:

    标签: powershell powershell-4.0 type-accelerators


    【解决方案1】:

    试试这个:

    function Some-Remote-Task([System.Management.Automation.Runspaces.PSSession]$Session, [String]$Target) {
      # Do stuff...
    }
    

    【讨论】:

    • 这行得通。我还不接受,因为我不知道这是否是最好的答案。
    • @Grallen 1) 您可以随时接受并在以后更改。 2)这是正确的答案。我不知道在哪里可以像这样单独使用[PSSession]。检查$mySession.GetType().FullName。这是$mySession.GetType().Namespace$mySession.GetType().Name 的串联。
    【解决方案2】:

    编辑:

    我现在可以正确使用[PSSession]了。

    通过结合 biantist 评论中链接中的信息:Type Accelerator

    这里有另一个答案:Simplify Your Script...

    我正确添加了类型加速器

    PS c:\> [PowerShell].Assembly.GetType("System.Management.Automation.TypeAccelerators")::add(“PSSession”,”System.Management.Automation.Runspaces.PSSession”)
    
    PS c:\> [PSSession]
    
    IsPublic IsSerial Name                                     BaseType
    -------- -------- ----                                     --------
    True     False    PSSession                                System.Object
    

    曾经:

    最后我使用了别名。发布给其他也喜欢干净外观的人。

    New-Alias PSSession System.Management.Automation.Runspaces.PSSession
    

    -ErrorAction SilentlyContinue 如果您继续重新运行相同的代码段,则在测试期间添加它很有用。

    【讨论】:

    • 就个人而言,我不鼓励这样做。我什至不确定这在您的代码中是如何工作的,因为别名用于命令/函数/cmdlet。你要找的是Type Accelerator
    • 以上评论是在编辑之前。现已实现类型加速器。
    猜你喜欢
    • 2016-08-07
    • 1970-01-01
    • 2011-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-19
    • 2011-06-06
    • 2014-05-11
    相关资源
    最近更新 更多