PowerShell queries the default application that opens a file
This article mainly introduces PowerShell to query the default application that opens a file. This article uses C # To Call The Windows API to achieve this requirement. For more information, see
Many file extensions are bound to one executable application. In this way, you can use Invoke-Item to open a document.
It is not troublesome to find a file with a given suffix that is opened by the default reference program. We can use the registry in Windows to program the solution. However, when scanning the registry, you should pay attention to the 32-bit and 64-bit machine issues. This is not the focus of this article.
Another way is to call the Windows API by taking the left-side navigation pane. The following example shows how to call the API. The biggest advantage of this approach is to leverage the operating system. The cost you pay is simply to use C # code to indirectly call functions in Windows API:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
$ Source = @" Using System; Using System. Text; Using System. Runtime. InteropServices; Public class Win32API { [DllImport ("shell32.dll", EntryPoint = "FindExecutable")] Public static extern long FindExecutableA (string lpFile, string lpDirectory, StringBuilder lpResult ); Public static string FindExecutable (string pv_strFilename) { StringBuilder objResultBuffer = new StringBuilder (1024 ); Long lngResult = 0; LngResult = FindExecutableA (pv_strFilename, string. Empty, objResultBuffer ); If (lngResult> = 32) { Return objResultBuffer. ToString (); } Return string. Format ("Error: ({0})", lngResult ); } } "@ Add-Type-TypeDefinition $ Source-ErrorAction SilentlyContinue $ FullName = 'C: \ Windows \ windowsupdate. Log' $ Executable = [Win32API]: FindExecutable ($ FullName) "$ FullName will be launched by $ Executable" |
The only restriction is that the FindExecutable () file to be checked exists. You cannot request the file extension only.
In addition, @ reidca reported that this method cannot detect files opened by the MMC add-on, such as cer and pfx certificate files, and the program will crash.