首页 > 解决方案 > 如何在 PowerShell 中获取可以与 Windows.UI.Notifications.ToastNotificationManager 的 GetForUser() 方法一起使用的 Windows.System.User?

问题描述

我一直在创建一个 powershell 脚本来显示 toast 通知,此代码有效,但 toastnotification 对象上有一种方法我不明白如何使用:

$Load = [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]
$Load = [Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime]
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($App).Show($ToastXml)

查看 [Windows.UI.Notifications.ToastNotificationManager] 对象,有一种名为“GetForUser()”的方法 https://docs.microsoft.com/en-us/uwp/api/windows.ui.notifications.toastnotificationmanager.getforuser ?view=winrt-19041

此方法需要一个 Windows.System.User 对象作为输入。 https://docs.microsoft.com/en-us/uwp/api/windows.system.user?view=winrt-19041

我试过下面的代码

$Load = [Windows.System.User, Windows.System, ContentType = WindowsRuntime]
$users = [Windows.System.User]::FindAllAsync()

$users 然后是一个没有任何方法的“System.__ComObject”。

所以问题是,我怎样才能在 PowerShell 中获得可以与 Windows.UI.Notifications.ToastNotificationManager 的 GetForUser() 方法一起使用的 Windows.System.User?

我也尝试过托管代码

$code = @"
using Windows.System;
namespace CUser
{
    public static class GetUsers{
        public static void Main(){
                IReadOnlyList<User> users = await User.FindAllAsync(UserType.LocalUser, UserAuthenticationStatus.LocallyAuthenticated);
                User user = users.FirstOrDefault();
        }
    }
    
}
"@
Add-Type -TypeDefinition $code -Language CSharp 

但这会产生错误:“类型或名称空间名称 'System' 不存在于名称空间 'Windows' 中(您是否缺少程序集引用?)”

我不确定哪个程序集或 dll 包含“Windows.System”引用。

标签: c#.netpowershelluwpdesktop-bridge

解决方案


我正在寻找类似的问题DeviceInformation并遇到了你的问题。解决方案原来在这篇博文中https://fleexlab.blogspot.com/2018/02/using-winrts-iasyncoperation-in.html

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
}

然后你可以FindAllAsync()像这样运行

$windowsSystemUserClass = [Windows.System.User, Windows.System, ContentType = WindowsRuntime]
$users = Await ([Windows.System.User]::FindAllAsync()) ([System.Collections.Generic.IReadOnlyList`1[Windows.System.User]])

推荐阅读