Assign filetype to a software by script

40 Views Asked by At

Would like to assign certain filetypes to a software by script (preferably by PowerShell or .reg) in Windows 11.

This PowerShell-Code worked fine over one year ago:

cmd /c "assoc .rhistory = rhistory_file"
cmd /c "ftype rhistory_file = "`"C:\Program Files\RStudio\rstudio.exe`" `"%1`"""

Tried also something like this:

$RStudioPath = "C:\Program Files\RStudio\rstudio.exe"
$FileType = ".rhistory"
$FileAssociation = [Microsoft.Win32.Registry]::ClassesRoot.CreateSubKey($FileType)
$FileAssociation.SetValue("", "RStudio.rhistory")
$FileAssociation.CreateSubKey("shell")
$Command = $FileAssociation.CreateSubKey("shell\open\command")
$Command.SetValue("", "`"$RStudioPath`" `"%1`"")

Can somebody help? Thank you.

1

There are 1 best solutions below

0
mklement0 On

Assuming that you've run them with elevation, i.e. as administrator, your commands look correct in principle.

However, on a per-filename-extension basis, user-specific overrides can be in place on a given machine, via File Explorer, namely:

  • If the current user has interactively chosen to always open a file with a given extension with a specific program, by right-clicking on such a file in File Explorer, selecting Open with > Choose another app, selecting the app of interest and then clicking on Always

  • Through a mechanism that is unclear to me, some applications - notably Visual Studio Code - manage to install such a persistent override even if you click on Just once or even just drag a file to an open Visual Studio Code windoe.

Either way, in order to undo such an override, you'll need to remove it from the registry at HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FileExts\<.extension>; in your case (using PowerShell's HKCU: drive to refer to the HKEY_CURRENT_USER hive):

#requires -RunAsAdmin
# Assumes that the key exists.
Remove-Item -Recurse HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.rhistory

The caveat is that you'll have to repeat the above whenever you (the current user) choses to open a file with the extension of interest with an application such as Visual Studio Code again - even with the intent of doing so ad hoc only.