How can I reference UWP classes in PowerShell

半世苍凉 提交于 2020-01-22 14:02:25

问题


I want to use a data type from a Universal Windows Platform library, how can I reference the containing namespace or assembly in PowerShell?

For example, I want to use the Windows.Data.Json.JsonObject class to parse me some json.

Had this been a regular .NET class, I would have done something like

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

But this strategy fails me with:

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

Now, it could be that I'm simply wrong in assuming that the assembly for the Windows.Data.Json namespace is Windows.Data.Json.dll, but the API reference does not actually seem to contain any references to containing files, leading me to believe that a dll file is actually not what I should be looking for.

I assume UWP has it's own cool GAC-like store from which I can load shared libraries, I simply just don't know how.

So basically my question is, how can I load a UWP shared library into PowerShell, and how should I reference UWP type literals?

Running PowerShell 5.1 on Windows 10 (build 1703)


回答1:


Shortly after posting this question, I stumbled on the GitHub repo for BurntToast, a module that allows raising UWP Toast Notifications from PowerShell, and it references the WinRT ToastNotificationManager type like this:

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

So, it looks like the syntax I'm after for UWP classes is:

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

With this in mind, I tried it with the example I gave in the question and lo and behold:

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"]

After referencing the type name once, I seem to be able to use the class name in a type literal without qualifying it as well:

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

Still very keen to find any documentation on this though



来源:https://stackoverflow.com/questions/45086059/how-can-i-reference-uwp-classes-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!