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

后端 未结 5 1144
名媛妹妹
名媛妹妹 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:21

    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`""
    }
    

提交回复
热议问题