【问题标题】:How can I reference UWP classes in PowerShell如何在 PowerShell 中引用 UWP 类
【发布时间】:2017-12-18 13:21:49
【问题描述】:

我想使用通用 Windows 平台库中的数据类型,如何在 PowerShell 中引用包含的命名空间或程序集?

例如,我想使用Windows.Data.Json.JsonObject class 来解析一些json。

如果这是一个常规的 .NET 类,我会做类似的事情

Add-Type -AssemblyName Windows.Data.Json
$jsonObject = [Windows.Data.Json.JsonObject]::Parse('{data:["powershell","rocks"]}')

但是这个策略让我失望了:

Add-Type : Cannot add type. The assembly 'Windows.Data.Json' could not be found.
At line:1 char:1
+ Add-Type -AssemblyName Windows.Data.Json
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Windows.Data.Json:String) [Add-Type], Exception
    + FullyQualifiedErrorId : ASSEMBLY_NOT_FOUND,Microsoft.PowerShell.Commands.AddTypeCommand

现在,我假设 Windows.Data.Json 命名空间的程序集是 Windows.Data.Json.dll 可能是完全错误的,但 API 引用实际上似乎不包含对包含文件的任何引用,这让我相信dll 文件实际上不是我应该寻找的。​​p>

我假设 UWP 有它自己很酷的类似 GAC 的存储,我可以从中加载共享库,我只是不知道如何。

所以基本上我的问题是,如何将 UWP 共享库加载到 PowerShell 中,我应该如何引用 UWP 类型文字?

在 Windows 10(内部版本 1703)上运行 PowerShell 5.1

【问题讨论】:

    标签: .net windows powershell uwp


    【解决方案1】:

    发布此问题后不久,我偶然发现了the GitHub repo for BurntToast,这是一个允许从 PowerShell 引发 UWP Toast 通知的模块,它引用 WinRT ToastNotificationManager 类型,如下所示:

    [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]
    

    所以,看起来我对 UWP 类的语法是:

    [<class name>,<namespace>,ContentType = WindowsRuntime]
    

    考虑到这一点,我用我在问题中给出的示例进行了尝试,你瞧:

    PS C:\> $jsonObjectClass = [Windows.Data.Json.JsonObject,Windows.Data.Json,ContentType=WindowsRuntime]
    PS C:\> $jsonObject = $jsonObjectClass::Parse('{"data":["powershell","rocks"]}')
    PS C:\> $jsonObject
    
    Key  Value                 
    ---  -----                 
    data ["powershell","rocks"]
    

    在引用类型名称一次后,我似乎可以在类型文字中使用类名称而无需对其进行限定:

    [Windows.Data.Json.JsonObject]::Parse("{}") # works without throwing errors now
    

    仍然非常渴望找到这方面的任何文档

    【讨论】:

    • 你会接受blog post吗?
    • @PeterTorr-MSFT 很好的参考,随意添加一个答案,概述 GetType/TypeInfo 参数的含义
    • 做得很好。奇怪的是,中间的字符串可以是 any 非空字符串。不幸的是,该技术似乎不适用于 PowerShell Core,并且无法直接加载底层程序集C:\WINDOWS\system32\WinMetadata\Windows.UI.winmd。博文链接现已失效,但这里有一个存档副本:web.archive.org/web/20190119013259/https://…
    猜你喜欢
    • 2020-09-07
    • 2019-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    • 2016-05-31
    相关资源
    最近更新 更多