82 lines
2.8 KiB
PowerShell
82 lines
2.8 KiB
PowerShell
|
function ConvertTo-HostsFileEntry {
|
||
|
<#
|
||
|
.SYNOPSIS
|
||
|
Convert the given record to a defined Hosts File Entry
|
||
|
|
||
|
.OUTPUTS
|
||
|
Returns a [object[]] of hosts entries.
|
||
|
#>
|
||
|
[CmdletBinding(DefaultParameterSetName = 'FromPipeline')]
|
||
|
[OutputType([string[]])]
|
||
|
param (
|
||
|
[Parameter(Mandatory = $false, ValueFromPipeline = $true, Position = 0, ParameterSetName = 'FromPipeline')]
|
||
|
[string]$RawRecord,
|
||
|
[Parameter(Mandatory = $true, ParameterSetName = 'Entries')]
|
||
|
[ValidateNotNullOrEmpty()]
|
||
|
[string]$IpAddress,
|
||
|
[Parameter(Mandatory = $true, ParameterSetName = 'Entries')]
|
||
|
[ValidateNotNullOrEmpty()]
|
||
|
[string]$Hostname,
|
||
|
[Parameter(Mandatory = $false, ParameterSetName = 'Entries')]
|
||
|
[string]$Comment
|
||
|
)
|
||
|
begin {
|
||
|
$disabledKey = "#DISABLED#"
|
||
|
}
|
||
|
process {
|
||
|
$workingIpAddress = $IpAddress
|
||
|
$workingHostname = $Hostname
|
||
|
$workingComment = $Comment
|
||
|
$isDisabled = $false
|
||
|
|
||
|
$commentSeparator = -1
|
||
|
if ($PSCmdlet.ParameterSetName -eq 'FromPipeline') {
|
||
|
$RawRecord = $RawRecord.Trim()
|
||
|
|
||
|
if ($RawRecord.StartsWith($disabledKey)) {
|
||
|
$isDisabled = $true
|
||
|
$RawRecord = $RawRecord.Substring($disabledKey.Length).Trim()
|
||
|
}
|
||
|
|
||
|
$commentSeparator = $RawRecord.IndexOf("#")
|
||
|
$workingComment = ""
|
||
|
$keep = $false
|
||
|
|
||
|
if ($commentSeparator -gt -1) {
|
||
|
$splits = $RawRecord -split '#',2
|
||
|
$workingComment = $splits[1].Trim()
|
||
|
$RawRecord = $splits[0].Trim()
|
||
|
}
|
||
|
|
||
|
if ($RawRecord.length -gt 0) {
|
||
|
$bits = [regex]::Split($RawRecord, "\s+")
|
||
|
if ($bits.count -gt 1) {
|
||
|
$workingIpAddress = $bits[0].Trim()
|
||
|
$workingHostname = $bits[1].Trim()
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
$keep = (($workingComment -imatch 'keep') -or ($workingIpAddress -eq $null))
|
||
|
$blankLine = ([string]::IsNullOrWhiteSpace($workingComment) -and [string]::IsNullOrWhiteSpace($workingIpAddress) -and ($commentSeparator -eq -1))
|
||
|
|
||
|
try {
|
||
|
$hostEntryObject = New-Object PSCustomObject -Property @{
|
||
|
IpAddress = $workingIpAddress
|
||
|
Hostname = $workingHostname
|
||
|
Comment = $workingComment
|
||
|
Keep = $keep
|
||
|
BlankLine = $blankLine
|
||
|
IsDisabled = $isDisabled
|
||
|
}
|
||
|
|
||
|
return $hostEntryObject
|
||
|
} catch {
|
||
|
Write-Warning "$logLead : Could not convert item to HostEntry object. Check error below. Returning `$null"
|
||
|
Write-ErrorObject -ErrorItem $PSItem
|
||
|
return $null
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
Set-Alias -Name New-HostsFileEntry -Value ConvertTo-HostsFileEntry
|