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