I have a very powershell script that works perfectly and does:
Param(
[string]$fileName
)
echo \"Woo I opened $fileName\"
When I run it on
Here's my remix of @Matthieu 's great remix of @Ansgar Weichar's great answer.
Matthieu's is set up for executables, and doesn't work for powershell scripts for the same reasons the OP describes.
Function Set-FileAssociationToPowerShellScript($extension, $pathToScript) {
# first create a filetype
$filetype = cmd /c "assoc $extension 2>NUL"
if ($filetype) {
# Association already exists: override it
$filetype = $filetype.Split('=')[1]
Write-Output "Using filetype $filetype"
}
else {
# Name doesn't exist: create it
# ".log.1" becomes "log1file"
$filetype = "$($extension.Replace('.', ''))file"
Write-Output "Creating filetype $filetype ($extension)"
cmd /c "assoc $extension=$filetype"
}
Write-Output "Associating filetype $filetype ($extension) with $pathToScript.."
cmd /c "ftype $filetype=powershell.exe -File `"$pathToScript`" `"%1`""
}
For those like me who got here looking for general file types associations, I ended up using this function:
Function Create-Association($ext, $exe) {
$name = cmd /c "assoc $ext 2>NUL"
if ($name) { # Association already exists: override it
$name = $name.Split('=')[1]
} else { # Name doesn't exist: create it
$name = "$($ext.Replace('.',''))file" # ".log.1" becomes "log1file"
cmd /c 'assoc $ext=$name'
}
cmd /c "ftype $name=`"$exe`" `"%1`""
}
I struggled with proper quoting from @Ansgar Wiechers's answer but finally got it right :)
I don't think you can do it through Windows UI.
The goal here is to associate a type with powershell.exe, arguments to which will be
To do this
Regedit.exe
. //disclaimer: you are editing Windows registry. Here be tigers..<extension>
, e.g. if you want to associate *.zbs - create a key .zbs
zbsfile
-- this is a reference linking your extension to a filetype.zbsfile
- this is your filetypezbsfile
shell
open
command
command
, set (default) value to e.g.powershell.exe -File "C:\path\to your\file.ps1" "%1"
That should work.
EDIT:
or (crazy idea), create a bat file doing just powershell.exe -File "C:\path\to your\file.ps1" "%%1"
and select it in Windows UI...
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
Here is a concrete answer tested under Windows 7 (but should work under 10 too). Open an administrative command shell and execute the following two lines once:
> assoc .ps1=Microsoft.PowerShellScript.1
> ftype Microsoft.PowerShellScript.1=%windir%\System32\WindowsPowerShell\v1.0\powershell.exe -File "%1"
Now PS1-files are executed by PowerShell 1.0 and not opened by Notepad anymore when double-clicked in the Explorer.