Search code examples
powershellwindows-10

How can I associate a file type with a powershell script?


I have a very powershell script that works perfectly and does:

Param(
  [string]$fileName
) 

echo "Woo I opened $fileName"

When I run it on the command line, it works:

my-script.ps1 .\somefile

Returns:

Woo I opened somefile

I would like to associate my-script.ps1 with a particular file type. I am attempting to do this via 'Open With' However:

  • Windows doesn't include Powershell scripts as 'Programs' (though it considers CMD and batch scripts as 'Programs')

enter image description here

  • When I pick 'All Files' instead, and pick my powershell script, Windows shows this message

enter image description here

How can I associate a file type with a Powershell script?


Solution

  • Use the proper tools for the job:

    cmd /c assoc .fob=foobarfile
    cmd /c ftype foobarfile=powershell.exe -File `"C:\path\to\your.ps1`" `"%1`"
    

    Note that both assoc and ftype are CMD-builtins, so you need to run them via cmd /c from PowerShell.

    For files without extension use this association:

    cmd /c assoc .=foobarfile