主頁 > 知識庫 > PowerShell實現(xiàn)查詢打開某個文件的默認應用程序

PowerShell實現(xiàn)查詢打開某個文件的默認應用程序

熱門標簽:網(wǎng)站排名優(yōu)化 百度競價排名 呼叫中心市場需求 地方門戶網(wǎng)站 服務外包 Linux服務器 AI電銷 鐵路電話系統(tǒng)

許多文件擴展名和一個可執(zhí)行應用程序綁定。正因為這樣你才可以使用Invoke-Item打開一個文檔。

要找出一個給定后綴名的文件是由那個默認引用程序打開它,并不麻煩。我們可以使用Windows系統(tǒng)中的注冊表,自行編程解決。但是在掃描注冊表時,要稍微留意一下32位和64位機器的問題,這不是本文重點,點到為止。

另外一種途徑,稍顯旁門左道,調用Windows API。下面的例子會演示如何調用。采取這種途徑最大的優(yōu)勢是借力于操作系統(tǒng)。而你的付出成本只是用C#代碼間接調用Windows API中的函數(shù)而已:

$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證書文件,程序會崩潰。

標簽:黃山 仙桃 湘潭 蘭州 崇左 衡水 湖南 銅川

巨人網(wǎng)絡通訊聲明:本文標題《PowerShell實現(xiàn)查詢打開某個文件的默認應用程序》,本文關鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權與本站無關。
  • 相關文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266