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

£可爱£侵袭症+ 提交于 2020-02-20 05:33:20

问题


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')

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

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


回答1:


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



回答2:


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 :)




回答3:


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

  1. The powershell script
  2. The target filename

To do this

  1. Launch Regedit.exe. //disclaimer: you are editing Windows registry. Here be tigers.
  2. Go to HKEY_CLASSES_ROOT (admin access, for all users) or HKEY_CURRENT_USER\SOFTWARE\Classes
  3. Create a key named .<extension>, e.g. if you want to associate *.zbs - create a key .zbs
  4. Set it's (default) value to something like zbsfile -- this is a reference linking your extension to a filetype.
  5. Create a key called zbsfile - this is your filetype
  6. Set (default) value to something readable, e.g. "This file is ZBS."
  7. Underneath create a tree of keys (examples are all around):

zbsfile shell open command

  1. Under command, set (default) value to e.g.
    powershell.exe -File "C:\path\to your\file.ps1" "%1"
    where %1 means the file user clicked

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...



来源:https://stackoverflow.com/questions/48280464/how-can-i-associate-a-file-type-with-a-powershell-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!