# Script to add the Hostname
# C:\Windows\System32\drivers\etc - Hosts has been added newly
Function Test-hostname {
## Allows the use of -WhatIf
[CmdletBinding(SupportsShouldProcess=$True)]
param(
## LogFile path for the transcript to be written to
[Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=0)]
$LogFile = ("C:\xyz\LOGS\"+"Addtohosts"+'.log'),
## All verbose outputs will get logged in the transcript($logFile)
[Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=2)]
$VerbosePreference = "Continue",
## All errors should be withheld from the console
[Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=3)]
$ErrorActionPreference = "SilentlyContinue"
## Hostname declaration and its IP
,[string]$DesiredIP = "00.00.00.00"
,[string]$Hostname = "kamalakannansccmblog.wordpress.com"
,[bool]$CheckHostnameOnly = $false
)
## Begin the timer
$Starters = (Get-Date)
## Check $VerbosePreference variable, and turns -Verbose on
Function global:Write-Verbose ( [string]$Message ) {
if ( $VerbosePreference -ne 'SilentlyContinue' ) {
Write-Host "$Message" -ForegroundColor 'Green'
}
}
Start-Transcript -Path $LogFile
Write-Verbose "Start time: $starters"
## Check $VerbosePreference variable, and turns -Verbose on
Function global:Write-Verbose ( [string]$Message ) {
if ( $VerbosePreference -ne 'SilentlyContinue' ) {
Write-Host "$Message" -ForegroundColor 'Green'
}
}
# Adds entry to the hosts file.
#Requires -RunAsAdministrator
$hostsFilePath = "$($Env:WinDir)\system32\Drivers\etc\hosts"
$hostsFile = Get-Content $hostsFilePath
Write-Host "About to add $desiredIP for $Hostname to hosts file" -ForegroundColor Gray
$escapedHostname = [Regex]::Escape($Hostname)
$patternToMatch = If ($CheckHostnameOnly) { ".*\s+$escapedHostname.*" } Else { ".*$DesiredIP\s+$escapedHostname.*" }
If (($hostsFile) -match $patternToMatch) {
Write-Host $desiredIP.PadRight(20," ") "$Hostname - not adding; already in hosts file" -ForegroundColor DarkYellow
}
Else {
Write-Host $desiredIP.PadRight(20," ") "$Hostname - adding to hosts file... " -ForegroundColor Yellow -NoNewline
Add-Content -Encoding UTF8 $hostsFilePath ("$DesiredIP".PadRight(20, " ") + "$Hostname")
Write-Host " done"
}
}
Test-hostname
Leave a comment