許多文件擴展名和一個可執行應用程序綁定。正因為這樣你才可以使用Invoke-Item打開一個文檔。
要找出一個給定后綴名的文件是由那個默認引用程序打開它,并不麻煩。我們可以使用Windows系統中的注冊表,自行編程解決。但是在掃描注冊表時,要稍微留意一下32位和64位機器的問題,這不是本文重點,點到為止。
另外一種途徑,稍顯旁門左道,調用Windows API。下面的例子會演示如何調用。采取這種途徑最大的優勢是借力于操作系統。而你的付出成本只是用C#代碼間接調用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" |
唯一有個限制,就是FindExecutable()需要檢查的文件是存在的,你不能只用文件擴展名去請求。
另外@reidca反饋說該方法不能檢測MMC加載項打開的文件,比如cer和pfx證書文件,程序會崩潰。