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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With