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

后端 未结 5 1153
名媛妹妹
名媛妹妹 2021-02-14 10:10

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

Param(
  [string]$fileName
) 

echo \"Woo I opened $fileName\"

When I run it on

5条回答
  •  星月不相逢
    2021-02-14 10:31

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

提交回复
热议问题