【问题标题】:Call Windows Runtime Classes from PowerShell从 PowerShell 调用 Windows 运行时类
【发布时间】:2013-01-01 23:59:14
【问题描述】:

有没有办法从 PowerShell 脚本调用 Windows 运行时 (WinRT) 类(或对象)?我知道你可以调用 COM 对象,WinRT 类应该被“公开”为......但到目前为止我的尝试都失败了......

这是我正在尝试的代码:

$lockscreen = New-Object -comObject Windows.System.UserProfile.LockScreen

这给了我以下错误:

New-Object : Retrieving the COM class factory for component with CLSID {00000000-0000-0000-0000-000000000000} failed
due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

有人知道我应该为 WinRT 类使用的正确“COM 类”吗?

【问题讨论】:

  • 嗯。好问题。至少您需要使用 PowerShell v3(无论如何都是 Win8 的默认设置)和 .NET 4.5。 Scott Hanselman 的这篇博文似乎表明它可以通过 C# 实现,因此它也应该可以通过 PowerShell 实现。 hanselman.com/blog/…

标签: powershell windows-runtime


【解决方案1】:

下面是一些似乎有效的 hacky:

PS> new-object "Windows.System.UserProfile.LockScreen,Windows.System.UserProfile,ContentType=WindowsRuntime"
new-object : Constructor not found. Cannot find an appropriate constructor for type
Windows.System.UserProfile.LockScreen,Windows.System.UserProfile,ContentType=WindowsRuntime.
At line:1 char:1
+ new-object "Windows.System.UserProfile.LockScreen,Windows.System.UserProfile,Con ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (:) [New-Object], PSArgumentException
    + FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand

PS> [Windows.System.UserProfile.LockScreen]::OriginalImageFile


AbsolutePath   : C:/Windows/Web/Screen/img100.png
AbsoluteUri    : file:///C:/Windows/Web/Screen/img100.png
LocalPath      : C:\Windows\Web\Screen\img100.png
Authority      :
HostNameType   : Basic
IsDefaultPort  : True
IsFile         : True
IsLoopback     : True
PathAndQuery   : C:/Windows/Web/Screen/img100.png
...

请注意,第一次调用失败是因为 LockScreen 没有构造函数,但该调用会拉入 WinRT 投影/元数据,以便您现在可以调用 LockScreen 类的静态方法/属性。

免责声明:我找不到任何关于此 New-Object 语法的文档,因此微软完全有可能更改它,因为它本质上是一个“隐藏”并且可能不完全开发的功能。

【讨论】:

【解决方案2】:

只需引用类型,即可“加载”程序集...

[Windows.System.UserProfile.LockScreen,Windows.System.UserProfile,ContentType=WindowsRuntime]
[Windows.System.UserProfile.LockScreen]::OriginalImageFile

如果您不希望在您的 powershell 结果中返回该类型,那么

$null = [Windows.System.UserProfile.LockScreen,Windows.System.UserProfile,ContentType=WindowsRuntime]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-12
    • 2021-10-02
    • 2010-11-09
    • 2018-10-12
    • 2017-06-22
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    相关资源
    最近更新 更多