PortValhalla/scripts/Windows/Scripts/AppAssociations.ps1

63 lines
2.8 KiB
PowerShell
Raw Normal View History

2023-07-26 10:53:38 +00:00
$null = New-Module {
class AppAssociations {
static $defaultAssociationsSelector = "/DefaultAssociations";
static $associationSelector = "./Association";
static [string] GetSelector([string] $identifier) {
2023-07-26 11:01:45 +00:00
return "$([AppAssociations]::associationSelector)[@Identifier='$identifier']";
}
static [xml] GetAppAssociations() {
2023-07-26 10:49:32 +00:00
[xml] $associations = [xml]::new();
$associations.LoadXml(((DISM /Online /Get-DefaultAppAssociations) | Select-Object -Skip 6 | Select-Object -SkipLast 2 | Out-String));
return $associations;
}
static SetAssociation([string] $identifier, [string] $progId, [string] $applicationName) {
$document = [AppAssociations]::GetAppAssociations();
$associations = $document.SelectSingleNode([AppAssociations]::defaultAssociationsSelector);
[System.Xml.XmlNode] $association = $null;
$candidates = $associations.SelectNodes([AppAssociations]::GetSelector($identifier));
if ($candidates.Count -eq 1) {
$association = $candidates[0];
} else {
2023-07-26 13:35:22 +00:00
$association = ($associations.SelectNodes([AppAssociations]::associationSelector) | Select-Object -Last 1).CloneNode($true);
$association.Identifier = $identifier;
$association = $associations.AppendChild($association);
}
$association.ProgId = $progId;
$association.ApplicationName = $applicationName;
[AppAssociations]::SaveAssociations($document);
}
static SaveAssociations([xml] $document) {
$associations = $document.SelectSingleNode([AppAssociations]::defaultAssociationsSelector);
$defaultAssociations = $associations.SelectNodes([AppAssociations]::associationSelector);
$defaultAssociations | ForEach-Object { $associations.RemoveChild($_); } | Sort-Object -Property "Identifier" | ForEach-Object { $associations.AppendChild($_); };
$configFile = New-TemporaryFile;
2023-07-26 12:49:03 +00:00
$writerSettings = [System.Xml.XmlWriterSettings]::new();
$writerSettings.Indent = $true;
$writerSettings.Encoding = [System.Text.UTF8Encoding]::new();
$writer = [System.Xml.XmlWriter]::Create($configFile.FullName, $writerSettings);
2023-07-26 16:28:31 +00:00
$document.Save($writer);
2023-07-26 13:26:02 +00:00
$writer.Dispose();
DISM /Online "/Import-DefaultAppAssociations:$($configFile.FullName)";
Remove-Item $configFile;
}
}
2023-07-26 10:53:30 +00:00
function Set-DefaultAppAssociation {
param (
[string] $Identifier,
[string] $ProgId,
[string] $ApplicationName
)
[AppAssociations]::SetAssociation($Identifier, $ProgId, $ApplicationName);
}
}