ps/Modules/Alkami.PowerShell.SDK/Public/Remove-HostsFileEntry.ps1

67 lines
2.5 KiB
PowerShell
Raw Normal View History

2023-05-30 22:51:22 -07:00
function Remove-HostsFileEntry {
<#
.SYNOPSIS
Returns all hosts file entries as a list of objects of the format:
A list of records of the format @{ Keep = $false; IpAddress = $null; Hostname = $null; Comment = $null; BlankLine = $false; }
.PARAMETER IpAddress
The IP Address of the relevant hosts entry
.PARAMETER Hostname
The hostname of the relevant hosts entry
.PARAMETER Force
Because some records are marked with the word keep to not be deleted
.OUTPUTS
A list of records of the format @{ Keep = $false; IpAddress = $null; Hostname = $null; Comment = $null; BlankLine = $false; }
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$IpAddress,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$Hostname,
[switch]$Force
)
$logLead = Get-LogLeadName
$records = Get-HostsFileAllRecords
$removedRecords = $records.Where({($_.IpAddress -eq $IpAddress) -and ($_.Hostname -eq $Hostname)})
foreach ($record in $removedRecords) {
Write-Host "$logLead : Removing: $(Format-HostsFileRecord -Record $record)"
}
$updatedRecords = $records.Where({!(($_.IpAddress -eq $IpAddress) -and ($_.Hostname -eq $Hostname))})
$keepRecords = $removedRecords.Where({$_.Keep})
if (!(Test-IsCollectionNullOrEmpty $keepRecords)) {
if ($Force) {
Write-Warning "$logLead : Skipping the following keep records"
} else {
Write-Warning "$logLead : Found Keep records in the remove-requested records. Re-adding to the updated records list. Use -Force to override."
}
$updatedKeepRecords = @()
foreach ($record in $keepRecords) {
$formattedRecord = Format-HostsFileRecord -Record $record
if ($Force) {
Write-Host "$logLead : Removing, not keeping: [$formattedRecord]"
} else {
Write-Host "$logLead : Keeping: [$formattedRecord]"
$newRecord = @{ Keep = $false; IpAddress = $null; Hostname = $null; Comment = $formattedRecord; BlankLine = $false; }
$updatedKeepRecords += $newRecord
}
}
$updatedRecords += $updatedKeepRecords
}
if ($removedRecords.Count -gt 0) {
Write-Host "$logLead : Removing: $removedRecordsCount records"
Save-CompleteHostsFile -Record $updatedRecords
} else {
Write-Warning "$logLead : No records found to remove"
}
}