萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

PowerShell 呼叫 Win32 API 查詢檔案關聯預設程式:FindExecutable 實作範例

Windows 檔案關聯資訊雖可查詢登錄表,但需處理 32/64 位重導向較繁瑣。直接 P/Invoke shell32.dll!FindExecutable 讓作業系統回傳預設開啟程式,程式碼極簡且自動處理架構差異。本文示範 PowerShell 內嵌 C# 簽名呼叫的完整範例。

內嵌 C# 定義 P/Invoke 簽名

$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"

限制與已知問題

  • 檔案必須實際存在,無法單純查詢副檔名關聯
  • 無法偵測 MMC 嵌入式管理單元開啟的檔案(如 .cer、.pfx),呼叫可能導致程式崩潰
  • 回傳值 >= 32 表示成功,錯誤代碼參考 SE_ERR_* 常數
copyright © 萬盛學電腦網 all rights reserved