在Powershell中关联文件类型的打开方式

 在Powershell中关联文件类型的打开方式

对当前用户有效

function Set-FileAssociation {
    param (
        [string]$fileExtension,
        [string]$exePath
    )
    
    # Create a new ProgID to avoid conflicts
    $progID = "CustomFileAssoc.$fileExtension"

    # Creating registry entries for file extension
    New-Item -Path "HKCU:\Software\Classes\$fileExtension" -Force
    New-ItemProperty -Path "HKCU:\Software\Classes\$fileExtension" -Name "(Default)" -Value $progID -Force

    # Create entries under the new ProgID
    New-Item -Path "HKCU:\Software\Classes\$progID" -Force
    New-ItemProperty -Path "HKCU:\Software\Classes\$progID" -Name "(Default)" -Value "$fileExtension File" -Force

    # Set the command to open the file
    New-Item -Path "HKCU:\Software\Classes\$progID\shell\open\command" -Force
    New-ItemProperty -Path "HKCU:\Software\Classes\$progID\shell\open\command" -Name "(Default)" -Value "`"$exePath`" `"%1`"" -Force

    Write-Host "$fileExtension files are now associated with $exePath."
}

# Example usage:
# Set-FileAssociation -fileExtension '.txt' -exePath 'D:\aa.exe'

函数说明:

  • 函数名Set-FileAssociation
  • 参数
    • $fileExtension:需要关联的文件扩展名。
    • $exePath:要关联的程序的完整路径。
  • 功能:该函数通过修改Windows注册表,将指定的文件扩展名关联到指定的程序。

使用示例:

假设需要关联 .txt 文件到 D:\aa.exe程序打开。使用时,请确保有修改注册表的权限。

广告

对所有用户有效,需要将注册表项从 HKCU: (当前用户) 更改为 HKLM: (本地机器)。这样,设置将应用于计算机上的所有用户。请确保你有管理员权限来修改 HKLM 下的注册表项,因为这通常需要更高的权限。

function Set-FileAssociationGlobal {
    param (
        [string]$fileExtension,
        [string]$exePath
    )
    
    # Create a new ProgID to avoid conflicts
    $progID = "GlobalFileAssoc.$fileExtension"

    # Creating registry entries for file extension in Local Machine
    New-Item -Path "HKLM:\Software\Classes\$fileExtension" -Force
    New-ItemProperty -Path "HKLM:\Software\Classes\$fileExtension" -Name "(Default)" -Value $progID -Force

    # Create entries under the new ProgID in Local Machine
    New-Item -Path "HKLM:\Software\Classes\$progID" -Force
    New-ItemProperty -Path "HKLM:\Software\Classes\$progID" -Name "(Default)" -Value "$fileExtension File" -Force

    # Set the command to open the file
    New-Item -Path "HKLM:\Software\Classes\$progID\shell\open\command" -Force
    New-ItemProperty -Path "HKLM:\Software\Classes\$progID\shell\open\command" -Name "(Default)" -Value "`"$exePath`" `"%1`"" -Force

    Write-Host "$fileExtension files are now globally associated with $exePath."
}

# Example usage:
# Run this script with administrative privileges:
# Set-FileAssociationGlobal -fileExtension '.txt' -exePath 'D:\aa.exe'

 

吴川斌

吴川斌

1 Comment

    Chauncy_li
  • 安装17.2, 安装过程找不到对应的vcredlis.msi。要怎么处理啊。
    运行了文件夹里的vcredist_x64.exe 文件,不知道生产的.msi 去哪里了?

Leave a Reply