ps/Modules/Alkami.PowerShell.Configuration/Private/Remove-AppSettingPrivate.ps1

72 lines
2.6 KiB
PowerShell
Raw Permalink Normal View History

2023-05-30 22:51:22 -07:00
function Remove-AppSettingPrivate {
<#
.SYNOPSIS
Removes an appSetting Key/Value pair in the specified file. Filepath defaults to the 64 bit machine config.
.DESCRIPTION
Remove an appSetting key/value pair in the specified config file if present.
Will default to the global 64 bit machine.config file if no config file value specified.
Will not tickle files where no values have changed.
Can connect to remote computers as well.
.PARAMETER Key
[string] The appSetting key
.PARAMETER FilePath
[string] The location to change settings in. Defaults to the global 64bit machine.config file.
.PARAMETER Force
[switch] Allow forcing the write of the process. This is due to the option for ShouldProcess.
#>
[CmdletBinding(SupportsShouldProcess, ConfirmImpact='None')]
param (
[Parameter(Mandatory = $true)]
[string]$Key,
[Parameter(Mandatory = $false)]
[Alias("Path")]
[string]$FilePath = (Get-DotNetConfigPath -use64Bit $true),
[Parameter(Mandatory = $false)]
[switch]$Force
)
$logLead = (Get-LogLeadName)
$dirty = $false
$appSettingsCollection = @($xml.SelectNodes('//appSettings'))
if (Test-IsCollectionNullOrEmpty $appSettingsCollection) {
Write-Warning "$logLead : No appSettings section found in file. Can not modify."
return
}
# In case there are more than one appSettings sections in the file
# There are edge cases where this may occur (notably some web.config)
# In the worst/best? case this just affects the one location
foreach($appSettingElement in $appSettingsCollection) {
$addNodes = $appSettingElement.SelectNodes('add')
foreach($node in $addNodes) {
if($node.key -eq $Key) {
Write-Host "$logLead : Found matching [$Key], removing"
$appSettingElement.RemoveChild($node) | Out-Null # in case it contains a password or something
$dirty = $true
}
}
}
if($dirty) {
Write-Verbose "$logLead : Saving config to path [$FilePath]"
if ($Force -or $PSCmdlet.ShouldProcess("Ready to write the file [$FilePath] contents?")) {
## Make sure the file gets saved with NoBOM
$utfNoBOM = New-Object System.Text.UTF8Encoding($false)
Save-XMLFile $FilePath $xml.OuterXml $utfNoBOM
} else {
Write-Host "$logLead : When confirmed, will write to file [$FilePath] with contents [[$($xml.OuterXml)]]"
}
} else {
Write-Verbose "$logLead : No changes were made to $FilePath"
}
}