如何将文件类型与Powershell脚本关联?

mik*_*ana 3 powershell windows-10

我有一个非常强大的shell脚本,可以完美地运行并且可以:

Param(
  [string]$fileName
) 

echo "Woo I opened $fileName"
Run Code Online (Sandbox Code Playgroud)

当我在命令行上运行它时,它将起作用:

my-script.ps1 .\somefile
Run Code Online (Sandbox Code Playgroud)

返回值:

Woo I opened somefile
Run Code Online (Sandbox Code Playgroud)

我想my-script.ps1与特定的文件类型关联。我正在尝试通过“打开方式”执行此操作,但是:

  • Windows不将Powershell脚本包含为“程序”(尽管它将CMD和批处理脚本视为“程序”)

在此处输入图片说明

  • 当我选择“所有文件”并选择我的Powershell脚本时,Windows会显示此消息

在此处输入图片说明

如何将文件类型与Powershell脚本关联?

Ans*_*ers 6

使用适当的工具进行工作:

cmd /c assoc .fob=foobarfile
cmd /c ftype foobarfile=powershell.exe -File `"C:\path\to\your.ps1`" `"%1`"
Run Code Online (Sandbox Code Playgroud)

请注意,两者assocftype都是CMD内置的,因此您需要通过cmd /cPowerShell 来运行它们。

对于不带扩展名的文件,请使用以下关联:

cmd /c assoc .=foobarfile
Run Code Online (Sandbox Code Playgroud)

  • 你是否知道 `assoc` 和 `ftype` 是否影响当前用户或本地机器?我不再记得,但我记得那咬我。 (2认同)