如何在Powershell中引用WinRT组件

时间:2015-01-21 14:01:21

标签: windows powershell windows-8 windows-runtime

我正在尝试在PowerShell中使用Windows.System命名空间(WinRT的一部分)。

而不是dll,程序集为winmd。将程序集加载到PowerShell中的两种方法似乎不起作用

#[System.Reflection.Assembly]::LoadFile("C:\Program Files (x86)\Windows Kits\8.0\References\CommonConfiguration\Neutral\Windows.winmd")

#Add-Type -Path "C:\Program Files (x86)\Windows Kits\8.0\References\CommonConfiguration\Neutral\Windows.winmd"

我知道使用Windows API比加载我的.NET代码有点棘手。我有使用win32部分的pinched代码,WinRT解决方案是否类似?

$script:nativeMethods = @();
function Register-NativeMethod([string]$dll, [string]$methodSignature)
{
    $script:nativeMethods += [PSCustomObject]@{ Dll = $dll; Signature = $methodSignature; }
}
function Add-NativeMethods()
{
    $nativeMethodsCode = $script:nativeMethods | % { "
        [DllImport(`"$($_.Dll)`")]
        public static extern $($_.Signature);
    " }

    Add-Type @"
        using System;
        using System.Runtime.InteropServices;
        public static class NativeMethods {
            $nativeMethodsCode
        }
"@
}

Register-NativeMethod "user32.dll" "int MessageBox (IntPtr hWnd, string text, string caption,int type)"
Add-NativeMethods
[NativeMethods]::MessageBox(0, "Please do not press this again.", "Attention", 0)| Out-Null

我的目标是在PowerShell中运行Windows.System.Launcher.LaunchFileAsync("C:\file");。如何加载我需要的WinRT组件?

1 个答案:

答案 0 :(得分:2)

要将WinRT二进制文件加载到PowerShell中,请使用以下示例:

> [Windows.Data.Json.JsonValue,Windows.Web,ContentType=WindowsRuntime]
> $value = new-object Windows.Data.Json.JsonObject
> $value.Stringify()

{}

我认为您需要StorageFile

> [Windows.System.Launcher,Windows.Web,ContentType=WindowsRuntime]
> [Windows.System.Launcher]::LaunchFileAsync

OverloadDefinitions
-------------------
static Windows.Foundation.IAsyncOperation[bool] LaunchFileAsync(Windows.Storage.IStorageFile file)
static Windows.Foundation.IAsyncOperation[bool] LaunchFileAsync(Windows.Storage.IStorageFile file, Windows.System.LauncherOptions options)

要创建一个,你可以这样做:

> [Windows.Management.Core.ApplicationDataManager,Windows.Web,ContentType=WindowsRuntime]
> $value = [Windows.Management.Core.ApplicationDataManager]::CreateForPackageFamily("BackgroundTaskApp_mxmz85hp10cp4")
> $asyncInfo = $value.LocalFolder.CreateFileAsync("foo.txt")

要使用await *Async()方法,您需要执行与create a wrapper类似的操作。