ps/Modules/Alkami.PowerShell.Configuration/Public/Get-AllAppSettingKeys.ps1
2023-05-30 22:51:22 -07:00

92 lines
3.2 KiB
PowerShell

function Get-AllAppSettingKeys {
<#
.SYNOPSIS
Returns an all appsetting keys from the specified file. Filepath defaults to the 64 bit machine config.
.PARAMETER filePath
[string] The location of the specific config file to check in
.PARAMETER ComputerName
[string] The remote computer to connect to. Defaults to localhost.
.OUTPUTS
Returns an array (empty as appropriate)
#>
[CmdletBinding()]
[OutputType([string[]])]
[OutputType([object[]])]
param (
[Parameter(Mandatory = $false)]
[Alias("Path")]
[string]$FilePath = (Get-DotNetConfigPath -use64Bit $true),
[Parameter(Mandatory = $false)]
[string]$ComputerName = "localhost"
)
$logLead = (Get-LogLeadName)
#region guard clauses
# If a computername was provided, modify the filepath to be a UNC path.
if((![string]::IsNullOrWhiteSpace($ComputerName)) -and ($ComputerName -ne "localhost")) {
$FilePath = (Get-UncPath -filePath $FilePath -ComputerName $ComputerName)
}
if (!(Test-Path -PathType Leaf -Path $FilePath)) {
Write-Warning "$logLead : Could not find a file at $FilePath. Execution cannot continue. Returning `$null"
return $null
}
Write-Verbose "$logLead : Reading Config file at $FilePath";
$xml = Read-XMLFile $FilePath
if(!$xml) {
throw "$logLead : Config at $FilePath could not be converted to xml."
}
Write-Verbose "$logLead : Ensuring configuration root node exists...";
if(!$xml.configuration){
throw "$logLead : How does $FilePath not have a root <configuration> element??"
}
#endregion guard clauses
$allKeys = @()
## Beware of the case of more than one appSettings element in case we run into issues, le sigh
## Let's go ahead and let the person reading the logs know that there were more than one section
$appSettingsCollection = @($xml.SelectNodes('//appSettings'))
if ($appSettingsCollection.Count -gt 1) {
Write-Warning "$logLead : More than one appSettings section found to manipulate in [$FilePath]"
foreach($appSettingElement in $appSettingsCollection) {
$fullPath = $appSettingElement.Name
$parentElement = $appSettingElement.ParentNode
while ($null -ne $parentElement) {
if($parentElement.Path) {
$fullPath = $parentElement.Name + '[path=' + $parentElement.Path + ']/' + $fullPath
} else {
$fullPath = $parentElement.Name + '/' + $fullPath
}
$parentElement = $parentElement.ParentNode
}
Write-Host "Too many appSettings: $fullPath"
}
}
if ($appSettingsCollection.Count -eq 0) {
## We don't have an appSettings element to work with
## Announce that, then return $null
Write-Warning "$logLead : Could not find an appSettings element at all in [$FilePath]. Returning an empty array."
return $allKeys
}
## Now that we have at least one location for settings, let's go see if we have an existing value
$appSettingsAdds = @($xml.configuration.SelectNodes("//appSettings/add"))
foreach($appSettingElement in $appSettingsAdds) {
$allKeys += $appSettingElement.Key
}
return $allKeys
}