function Add-HostsFileContent { <# .SYNOPSIS Adds Strings to the Hosts File #> [CmdletBinding()] Param( [Parameter(Mandatory = $true)] [string[]]$contentToAdd, [Parameter(Mandatory = $false)] [string]$hostsPath = "$env:windir\System32\Drivers\etc\hosts", [Parameter(Mandatory = $false)] [Alias("Force")] [switch]$forceWrite ) $logLead = (Get-LogLeadName) $hostsContent = Get-HostsFileContent $hostsPath $builder = New-Object System.Text.StringBuilder(($hostsContent -join [Environment]::NewLine)) $builder.AppendLine() | Out-Null $hostsFileIsDirty = $false [Regex]$uncommentedIPRegex = "^[^\#]?(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b" foreach ($hostsEntry in $contentToAdd) { # Remove comments from the line. $commentSearch = $hostsEntry.IndexOf("#"); if($commentSearch -ge 0) { $hostsEntry = $hostsEntry.Substring(0, $commentSearch); } if ($hostsEntry -match $uncommentedIPRegex) { $ipFromContent = ($MATCHES.Values | Select-Object -First 1) if ($hostsContent -match $ipFromContent -and !($forceWrite.IsPresent)) { Write-Warning ("$logLead : A hosts entry already exists for IP address: {0}" -f $ipFromContent) continue } } else { Write-Warning ("$logLead : Could not find a valid IP address in content: {0}" -f $hostsEntry) continue } Write-Output ("$logLead : Adding Hosts Entry : {0}" -f $hostsEntry.ToString()) $hostsFileIsDirty = $true $builder.AppendLine($hostsEntry.ToString()) | Out-Null } ## Ensure that a path exists. If the value is $null or empty, then we want "do we have a host path" to be $false, so invert the "is it null/empty" check value ## TODO: cbrand ~ Do we want to add a Test-Path here instead? $hasHostsPath = !([string]::IsNullOrEmpty($hostsPath)) if ($hostsFileIsDirty -and $hasHostsPath) { Write-Output ("$logLead : Saving Modified Hosts File to {0}" -f $hostsPath) $finalOutput = $builder.ToString().TrimEnd(); [System.IO.File]::WriteAllLines($hostsPath, $finalOutput); } else { Write-Output ("$logLead : No changes made to hosts file") } }