On Windows, if you right click a file in explorer, you get a context menu. One of the entries is Open With
> Choose another program
. Clicking this opens a GUI to choose a program to open the file. Is it possible to open this GUI from the command line?
CodePudding user response:
There is a shell API for this purpose that can be used from PowerShell using P/Invoke. This is more reliable than the often suggested but undocumented "RunDll32.exe OpenAs_RunDLL" method (see this answer for details why it is bad).
Save this code as "openas.ps1":
param (
[Parameter(Mandatory)]
[String] $Path
)
$ErrorActionPreference = 'Stop'
Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
public class ShellOpenWith {
[DllImport("shell32.dll", EntryPoint = "SHOpenWithDialog", CharSet = CharSet.Unicode)]
private static extern int SHOpenWithDialog(IntPtr hWndParent, ref tagOPENASINFO oOAI);
// http://msdn.microsoft.com/en-us/library/windows/desktop/bb773363(v=vs.85).aspx
private struct tagOPENASINFO
{
[MarshalAs(UnmanagedType.LPWStr)]
public string cszFile;
[MarshalAs(UnmanagedType.LPWStr)]
public string cszClass;
[MarshalAs(UnmanagedType.I4)]
public tagOPEN_AS_INFO_FLAGS oaifInFlags;
}
[Flags]
private enum tagOPEN_AS_INFO_FLAGS
{
OAIF_ALLOW_REGISTRATION = 0x00000001, // Show "Always" checkbox
OAIF_REGISTER_EXT = 0x00000002, // Perform registration when user hits OK
OAIF_EXEC = 0x00000004, // Exec file after registering
OAIF_FORCE_REGISTRATION = 0x00000008, // Force the checkbox to be registration
OAIF_HIDE_REGISTRATION = 0x00000020, // Vista : Hide the "always use this file" checkbox
OAIF_URL_PROTOCOL = 0x00000040, // Vista : cszFile is actually a URI scheme; show handlers for that scheme
OAIF_FILE_IS_URI = 0x00000080 // Win8 : The location pointed to by the pcszFile parameter is given as a URI
}
public static void DoOpenFileWith(string sFilename, IntPtr hwndParent = new IntPtr())
{
tagOPENASINFO oOAI = new tagOPENASINFO();
oOAI.cszFile = sFilename;
oOAI.cszClass = String.Empty;
oOAI.oaifInFlags = tagOPEN_AS_INFO_FLAGS.OAIF_ALLOW_REGISTRATION | tagOPEN_AS_INFO_FLAGS.OAIF_EXEC;
SHOpenWithDialog(hwndParent, ref oOAI);
}
}
'@
[ShellOpenWith]::DoOpenFileWith( $path )
Run this script from the commandline like this:
powershell.exe c:\openas.ps1 c:\file.txt