2017-07-13 27 views
7

我想從通用Windows平臺庫中使用數據類型,如何在PowerShell中引用包含的名稱空間或程序集?如何在PowerShell中引用UWP類

例如,我想用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文件實際上不是我應該查找的內容。

我認爲UWP有它自己的酷GAC樣商店,我可以從中加載共享庫,我只是不知道如何。

所以基本上我的問題是,如何加載UWP共享庫到PowerShell中,以及如何引用UWP類型文字?

在Windows 10運行PowerShell的5.1(版本1703)

回答

6

不久發佈這個問題後,我偶然在the GitHub repo for BurntToast,一個模塊,它可以從PowerShell的提高UWP敬酒通知,並引用了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 

還是很敏銳地發現這個任何文件雖然

+1

你會接受一個[博客文章(https://blogs.msdn.microsoft.com/ptorr/ 2012/5月27日/加載-WinRT的類型-經由反射式 - 窗口8 /)? –

+0

@ PeterTorr-MSFT很好的參考資料,請隨時添加一個答案,概述GetType/TypeInfo參數的含義 –