在 PowerShell 中使用 UWP API 命名空间

grw*_*rwa 5 powershell windows-10 uwp

我一直在寻找如何在 PowerShell 中使用命名空间来处理 Windows 10 锁定屏幕并遇到了这个答案:https : //superuser.com/a/1062551/700258,但是它没有说明如何导入或将该命名空间添加到 PowerShell 以供使用。我尝试为程序集查找引用的 DLL 文件,但它们不在我的计算机上。当我看到它们是 Windows 桌面扩展 API 的一部分时,我出去下载了 Windows 10 SDK,但 DLL 文件也不在其中。如何在 PowerShell 脚本中使用 Windows.System.UserProfile 命名空间中的此 LockScreen 类?

Ben*_*n N 10

首先,您需要告诉 PowerShell 您要使用 UWP 类:

[Windows.System.UserProfile.LockScreen,Windows.System.UserProfile,ContentType=WindowsRuntime] | Out-Null
Run Code Online (Sandbox Code Playgroud)

第一部分是类名,第二部分是 UWP 命名空间,第三部分只是说它是一个 UWP 类。加载类型后,您可以通过其名称引用该类型(仅第一部分:[Windows.System.UserProfile.LockScreen]在本例中。)

下一个技巧是 Windows 运行时方法是异步的,并且使用与 .NET Framework 方法不同的异步任务类。从 PowerShell 调用它们需要一些额外的基础设施,我最初为另一个答案开发了这些基础设施:

Add-Type -AssemblyName System.Runtime.WindowsRuntime
$asTaskGeneric = ([System.WindowsRuntimeSystemExtensions].GetMethods() | ? { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' })[0]
Function Await($WinRtTask, $ResultType) {
    $asTask = $asTaskGeneric.MakeGenericMethod($ResultType)
    $netTask = $asTask.Invoke($null, @($WinRtTask))
    $netTask.Wait(-1) | Out-Null
    $netTask.Result
}
Function AwaitAction($WinRtAction) {
    $asTask = ([System.WindowsRuntimeSystemExtensions].GetMethods() | ? { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and !$_.IsGenericMethod })[0]
    $netTask = $asTask.Invoke($null, @($WinRtAction))
    $netTask.Wait(-1) | Out-Null
}
Run Code Online (Sandbox Code Playgroud)

Await可用于调用返回 的函数IAsyncOperation,即产生值的函数。它采用 WinRT 任务对象和输出类型。AwaitAction可用于调用返回 的函数IAsyncAction,即那些只执行某些操作而不返回结果的函数。它只需要 WinRT 任务对象。

对于这个应用程序,我们也需要StorageFile可访问的类型:

[Windows.Storage.StorageFile,Windows.Storage,ContentType=WindowsRuntime] | Out-Null
Run Code Online (Sandbox Code Playgroud)

现在我们可以开始调用一些函数了。首先我们使用GetFileFromPathAsync获取IStorageFile所需锁屏图像的实例:

$image = Await ([Windows.Storage.StorageFile]::GetFileFromPathAsync('C:\path\to\image.ext')) ([Windows.Storage.StorageFile])
Run Code Online (Sandbox Code Playgroud)

最后,我们将该图像传递SetImageFileAsync给设置锁屏背景:

AwaitAction ([Windows.System.UserProfile.LockScreen]::SetImageFileAsync($image))
Run Code Online (Sandbox Code Playgroud)

更改应立即生效。

  • 在 PowerShell、Async、Lock Screens 和 Registry 的雷区中搜索了数小时后,您的答案来自湖泊,并沐浴在完美之光中。老实说,这很奇怪。我正在寻找 PowerShell 和 Async 的东西,因为我试图解决的实际问题是使用 SetImageFileAsync 编写用户锁屏更改脚本,而您设法同时回答了两半。xxx ;-) (2认同)

归档时间:

查看次数:

4476 次

最近记录:

4 年,8 月 前