Search code examples
windowspowershellwindows-8windows-runtime

How to reference WinRT components in Powershell


I'm trying to use the Windows.System namespace, part of WinRT, in PowerShell.

Instead of a dll, the assembly comes as a winmd. The two ways of loading assemblies into PowerShell don't seem to work

#[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"

I am aware that using Windows API's is a bit trickier than loading my .NET code. I have pinched code for using parts of the win32, would a WinRT solution be similar?

$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

My goal is to run Windows.System.Launcher.LaunchFileAsync("C:\file"); in PowerShell. How can I load the WinRT components I need?


Solution

  • To load WinRT binaries into PowerShell use this example:

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

    I think you will need a 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)
    

    To create one, you may do something like this:

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

    To await *Async() methods, you will need to do something like to create a wrapper.