Windows 檔案關聯資訊雖可查詢登錄表,但需處理 32/64 位重導向較繁瑣。直接 P/Invoke shell32.dll!FindExecutable 讓作業系統回傳預設開啟程式,程式碼極簡且自動處理架構差異。本文示範 PowerShell 內嵌 C# 簽名呼叫的完整範例。
$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 filePath) {
var buffer = new StringBuilder(1024);
long result = FindExecutableA(filePath, string.Empty, buffer);
if (result >= 32) return buffer.ToString();
return string.Format("Error: ({0})", result);
}
}
"@
Add-Type -TypeDefinition $Source -ErrorAction SilentlyContinue
$FullName = 'C:\Windows\windowsupdate.log'
$Executable = [Win32API]::FindExecutable($FullName)
"$FullName will be launched by $Executable"
.cer、.pfx),呼叫可能導致程式崩潰>= 32 表示成功,錯誤代碼參考 SE_ERR_* 常數