当前位置: 代码网 > it编程>前端脚本>Powershell > PowerShell实现查询打开某个文件的默认应用程序

PowerShell实现查询打开某个文件的默认应用程序

2024年05月18日 Powershell 我要评论
许多文件扩展名和一个可执行应用程序绑定。正因为这样你才可以使用invoke-item打开一个文档。要找出一个给定后缀名的文件是由那个默认引用程序打开它,并不麻烦。我们可以使用windows系统中的注册

许多文件扩展名和一个可执行应用程序绑定。正因为这样你才可以使用invoke-item打开一个文档。

要找出一个给定后缀名的文件是由那个默认引用程序打开它,并不麻烦。我们可以使用windows系统中的注册表,自行编程解决。但是在扫描注册表时,要稍微留意一下32位和64位机器的问题,这不是本文重点,点到为止。

另外一种途径,稍显旁门左道,调用windows api。下面的例子会演示如何调用。采取这种途径最大的优势是借力于操作系统。而你的付出成本只是用c#代码间接调用windows api中的函数而已:

$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证书文件,程序会崩溃。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com