Email Value From Variable & Hyperlink - email

From within PowerShell, I know how to send a basic email. But with my syntax below, how could I append to the body of the email each $QueryName and each $RowCount and add a hyperlink to the value contained in $FPath\$FormattedDate\so the body of email would look like this:
$QueryName - $RowCount
(or with actual data)
Santa - 14
Mickey - 12
Mars - 2
Here is my current PS script
Function Execute-SQLquery {
param ($QueryName, $QueryString)
$server = "Server"
$database = "DB1"
$FPath = "C:\Testing"
#Setting additional variables
$extension = ".csv"
$date = Get-Date -f 'MM.dd.yy'
$FormattedDate = Get-Date -f 'MM.dd.yy'
$connectionTemplate = "Data Source={0};Integrated Security=SSPI;Initial Catalog={1};"
$connectionString = [string]::Format($connectionTemplate, $server, $database)
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$command = New-Object System.Data.SqlClient.SqlCommand
$command.CommandText = $QueryString
$command.Connection = $connection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $command
$DataSet = New-Object System.Data.DataSet
$rowCount = $SqlAdapter.Fill($DataSet)
if(!(Test-Path -path "$FPath\$FormattedDate\")){New-Item "$FPath\$FormattedDate\" -type directory}
if ($rowCount -gt 0)
{
if ($QueryName -eq "Santa")
{
$extractFile = "C:\Testing\TemplateFiles\Santa.csv"
[System.IO.Directory]::CreateDirectory("$FPath\$FormattedDate\Santa\")
Write-Host $rowCount -fore Red
$dirName = "$FPath\$FormattedDate\Santa\"
$filename = [IO.Path]::GetFileNameWithoutExtension($extractFile) + "_$date" + [IO.Path]::GetExtension($extractFile)
$extractFile = Join-Path $dirname $filename
}
if ($QueryName -eq "Mickey")
{
$extractFile = "C:\Testing\TemplateFiles\Mickey.csv"
[System.IO.Directory]::CreateDirectory("$FPath\$FormattedDate\Mickey\")
Write-Host $rowCount -fore Red
$dirName = "$FPath\$FormattedDate\Mickey\"
$filename = [IO.Path]::GetFileNameWithoutExtension($extractFile) + "_$date" + [IO.Path]::GetExtension($extractFile)
$extractFile = Join-Path $dirname $filename
}
if ($QueryName -eq "Mars")
{
$extractFile = "C:\Testing\TemplateFiles\Mickey\Mars.csv"
[System.IO.Directory]::CreateDirectory("$FPath\$FormattedDate\Mars\")
Write-Host $rowCount -fore Red
$dirName = "$FPath\$FormattedDate\Mars\"
$filename = [IO.Path]::GetFileNameWithoutExtension($extractFile) + "_$date" + [IO.Path]::GetExtension($extractFile)
$extractFile = Join-Path $dirname $filename
}
$DataSet.Tables[0] | Export-Csv $extractFile -NoTypeInformation
}
$connection.Close()
}

First up, since the only thing that changes based on $QueryName are direct references to the value in $QueryName and the $extractFile, you'd be better off not repeating that entire block.
For the mail message, you can use Send-MailMessage.
To add a link to a local file resource, use the file:/// scheme prefix and change all backslashes (\) to forward slashes (/), ie. file:///C:/Document/Path.ext, or in your example "file:///$("$FPath\$FormattedDate" -replace '\','/')":
Function Execute-SQLquery {
param ($QueryName, $QueryString)
# up to this point no change is required
if ($rowCount -gt 0)
{
$extractFile = switch($QueryName){
"Santa" { "C:\Testing\TemplateFiles\Santa.csv" }
"Mickey" { "C:\Testing\TemplateFiles\Mickey.csv" }
"Mars" { "C:\Testing\TemplateFiles\Mars\Mickey.csv" }
default { throw "Illegal QueryName" }
}
[System.IO.Directory]::CreateDirectory("$FPath\$FormattedDate\$QueryName\")
Write-Host $rowCount -fore Red
$dirName = "$FPath\$FormattedDate\$QueryName\"
$filename = [IO.Path]::GetFileNameWithoutExtension($extractFile) + "_$date" + [IO.Path]::GetExtension($extractFile)
$extractFile = Join-Path $dirname $filename
$DataSet.Tables[0] | Export-Csv $extractFile -NoTypeInformation
$EmailBody = #'
Here are the results:
{0} - {1}
Find the documents here
'# -f $QueryName,$rowCount,$("$FPath\$FormattedDate" -replace '\','/')
Send-MailMessage -From "me#company.example" -To "you#company.example" -Body $EmailBody -BodyAsHtml:$true -Subject "Data extracted!" -SmtpServer "your.mail.server.company.example"
}
$connection.Close()
}

Related

Need to append this powershell script, not sure what to do

I need some help expanding on this script. Basically, I need to add when the $inputFileName = 'Report.txt' is not in its default dir when the script runs every morning the job spits out an e-mail saying no file to process, and then the job stops. What I am seeing is when there is no file in the source dir every now and then, the job runs attaching a blank .xls file that is of no use. I appreciate ANY help in advance!
$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue"
Start-Transcript -path C:\PATH\Logoutput.txt -append
$emailFilePath = 'C:\PATH\PATH\'
$inputFilePath = 'C:\PATH\PATH\Upload'
$inputFileName = 'Report.txt'
$inputFile = Join-Path $inputFilePath $inputFileName
$outputFileName = 'Report.csv'
$outputFilePath = 'C:\PATH\PATH\Send'
$OutputFile = Join-Path $outputFilePath $outputFileName
$folder = 'C:\PATH\PATH\Upload'
$filter = 'Report.txt'
$destination = $outputFilePath
$dateTime1 = Get-Date -Format s
Write-Host "The file was received: $dateTime1"
Import-CSV $inputFile -Delimiter "`t" -Header "Value 1" , "Value 2" , "Value 3" , "Value 4" , "Value 5" | Tee-Object -Variable Report.txt | Export-CSV $OutputFile -Delimiter "," -NoTypeInformation
$xl = new-object -comobject excel.application
$xl.visible = $false
$Workbook = $xl.workbooks.open("$OutputFile")
$Worksheets = $Workbooks.worksheets
$Workbook.SaveAs("$outputFilePath\Report.xls",1)
$Workbook.Saved = $True
$xl.Quit()
$objExcel = new-object -comobject excel.application
$objExcel.Visible = $false
$objWorkbook = $objExcel.Workbooks.open("$outputFilePath\Report.xls")
$objWorksheet = $objWorkbook.Worksheets.Item(1)
$objRange = $objWorksheet.UsedRange
[void] $objRange.EntireColumn.Autofit()
$objWorkbook.SaveAs("$outputFilePath\Report.xlsx",51)
$objWorkbook.Saved = $True
$objExcel.Quit()
$fromaddress = "user#domain.com"
$toaddress = "user#domain.com"
$bccaddress = ""
$CCaddress = "user#domain.com"
$Subject = "Here Is The Report"
$body = get-content $emailFilePath\content.htm
$attachment = "$outputFilePath\Report.xlsx"
$smtpserver = "smtpdomain"
$message = new-object System.Net.Mail.MailMessage
$message.From = $fromaddress
$message.To.Add($toaddress)
$message.CC.Add($CCaddress)
#$message.Bcc.Add($bccaddress)
$message.IsBodyHtml = $True
$message.Subject = $Subject
$attach = new-object Net.Mail.Attachment($attachment)
$message.Attachments.Add($attach)
$message.body = $body
$smtp = new-object Net.Mail.SmtpClient($smtpserver)
$smtp.Send($message)
$dateTime2 = Get-Date -Format s
Write-Host "The file was parsed and emailed at $dateTime2"
Start-Sleep -Seconds 60
$message.Dispose()
Start-Sleep -Seconds 60
kill -processname Excel
Start-Sleep -Seconds 60
Remove-Item "C:\PATH\PATH\Send\*.*"
$filenameFormat = "Report" + "" + (Get-Date -Format "yyyy-MM-dd") + ".txt"
$updatedFile = "C:\PATH\PATH\Upload\" + $filenameFormat
Rename-Item -Path "C:\PATH\PATH\Upload\Report.txt" -NewName $filenameFormat
Move-Item -Path $updatedFile -Destination C:\PATH\PATH\ArchivedReportData
Stop-Transcript
exit
You need to test for the file before processing as follows:
If ( -not (Test-Path -Path "inputFile")) {
#Write your file not found logic/messages here
Exit
}
Import-CSV $inputFile -Delimiter "`t" -Header "Value 1" , "Value 2" , "Value 3" , "Value 4" , "Value 5" | Tee-Object -Variable Report.txt | Export-CSV $OutputFile -Delimiter "," -NoTypeInformation
$dateTime1 = Get-Date -Format s
Write-Host "The file was received: $dateTime1"
...
HTH

Invalid Characters in Add-PnPFile stream output

I am trying to take a string and write it to a new file (or update an existing file) in SharePoint Online. Using the following code, the file is created, but it is full of invalid characters (? inside a diamond) and the string "test string" does not appear.
$RootPath = '/Shared Documents/General'
$FolderName = 'Customer'
$FileName = 'test.txt'
$fileContent = 'test string'
$Size = 8192;
[System.IO.MemoryMappedFiles.MemoryMappedFile]$MMF = [System.IO.MemoryMappedFiles.MemoryMappedFile]::CreateNew($FileName, $Size);
If ($Null -eq $MMF) {
Return;
}
$Stream = $MMF.CreateViewStream();
$StreamWriter = [System.IO.StreamWriter]::new($Stream);
$StreamWriter.Write($FileContent);
Add-PnPFile -FileName $FileName -Folder "$RootPath/$FolderName" -Stream $Stream
$StreamWriter.Dispose();
$Stream.Dispose();
$MMF.Dispose();
Am I encoding the string incorrectly or what?
Sample script for your reference.
#region Variables
$Username = "user#xxx.onmicrosoft.com"
$Password = "Password"
$siteURL = "https://xxx.sharepoint.com/sites/lee"
#endregion Variables
#region Credentials
[SecureString]$SecurePass = ConvertTo-SecureString $Password -AsPlainText -Force
[System.Management.Automation.PSCredential]$PSCredentials = New-Object System.Management.Automation.PSCredential($Username, $SecurePass)
#endregion Credentials
Connect-PnPOnline -Url $siteURL -Credentials $PSCredentials
$RootPath = '/Shared Documents/General'
$FolderName = 'Customer'
$FileName = 'test.txt'
$fileContent = 'test string'
$Stream = [IO.MemoryStream]::new([Text.Encoding]::UTF8.GetBytes($fileContent))
# $Size = 8192;
# [System.IO.MemoryMappedFiles.MemoryMappedFile]$MMF = [System.IO.MemoryMappedFiles.MemoryMappedFile]::CreateNew($FileName, $Size);
# If ($Null -eq $MMF) {
# Return;
# }
# $Stream = $MMF.CreateViewStream();
# $StreamWriter = [System.IO.StreamWriter]::new($Stream);
# $StreamWriter.Write($FileContent);
Add-PnPFile -FileName $FileName -Folder "$RootPath/$FolderName" -Stream $Stream
# $StreamWriter.Dispose();
# $Stream.Dispose();
# $MMF.Dispose();
Write-Host "----"

How to Export-Csv with variables?

I'm trying to write 8 variables into an CSV file with PowerShell, but it just ends up as ,,,,,,, instead of var1,var2,var3,var4,var5,var6,var7,var8
My code is as follows:
$newRow = "{0},{1},{2},{3},{4},{5},{6},{7}" -f $var1,$var2,$var3,$var4,$var5,$var6,$var7,$var8
$newRow = $newRow -Replace "`t|`n|`r",""
$newRow = $newRow -Replace " ;|; ",";"
$newRow += "`n"
$newRow | Export-Csv -Path $file -Append -noType -Force
Without -Force I get the following error message:
Export-Csv : Cannot append CSV content to the following file: C:\result.txt. The
appended object does not have a property that corresponds to the following column:
var1. To continue with mismatched properties, add the -Force parameter, and then
retry the command.
At C:\Test.ps1:72 char:12
+ $newRow | Export-Csv -Path $file -Append -noType
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (var1:String) [Export-Csv], InvalidOperationException
+ FullyQualifiedErrorId : CannotAppendCsvWithMismatchedPropertyNames,Microsoft.PowerShell.Commands.ExportCsvCommand
EDIT:
Script:
$startInfo = New-Object System.Diagnostics.ProcessStartInfo
$startInfo.FileName = "powershell.exe"
$startInfo.Arguments = 'C:\zabbix\script\zabbix_vbr_job.ps1 "Discovery"'
$startInfo.RedirectStandardOutput = $true
$startInfo.UseShellExecute = $false
$startInfo.CreateNoWindow = $false
#$startInfo.Username = "DOMAIN\Username"
#$startInfo.Password = $password
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $startInfo
$process.Start() | Out-Null
$discoveryJson = $process.StandardOutput.ReadToEnd()
$process.WaitForExit()
cls
$discovery = $discoveryJson | ConvertFrom-Json
$file = "C:\zabbix\script\result.txt"
function RunScript ($param, $id)
{
$startInfo = New-Object System.Diagnostics.ProcessStartInfo
$startInfo.FileName = "powershell.exe"
$startInfo.Arguments = "C:\zabbix\script\zabbix_vbr_job.ps1 '$param' '$id'"
$startInfo.RedirectStandardOutput = $true
$startInfo.UseShellExecute = $false
$startInfo.CreateNoWindow = $false
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $startInfo
$process.Start() | Out-Null
$output = $process.StandardOutput.ReadToEnd()
$process.WaitForExit()
return $output
}
$fileContent = Import-csv $file
$NewCSVObject = #()
foreach($obj in $discovery.data)
{
$index = [array]::indexof($discovery.data, $obj)
Write-Host $index "/" $discovery.data.count
#Write-Host (RunScript "Result" $obj.JOBID )
$Result = RunScript "Result" $obj.JOBID
#Write-Host $Result
$RunStatus = RunScript "RunStatus" $obj.JOBID
#Write-Host $RunStatus
$IncludedSize = RunScript "IncludedSize" $obj.JOBID
#Write-Host $IncludedSize
$ExcludedSize = RunScript "ExcludedSize" $obj.JOBID
#Write-Host $ExcludedSize
$VmCount = RunScript "VmCount" $obj.JOBID
#Write-Host $VmCount
$Type = RunScript "Type" $obj.JOBID
#Write-Host $Type
$RunningJob = "RunningJob"#RunScript "RunningJob" $obj.JOBID
#Write-Host $RunningJob
#$newRow = New-Object PsObject -Property #{ JobID = $obj.JOBID ; Result = $Result ; RunStatus = $RunStatus ; IncludedSize = $IncludedSize ; ExcludedSize = $ExcludedSize ; VmCount = $VmCount ; Type = $Type ; RunningJob = $RunningJob }
$newRow = "{0},{1},{2},{3},{4},{5},{6},{7}" -f $obj.JOBID,$Result,$RunStatus,$IncludedSize,$ExcludedSize,$VmCount,$Type,$RunningJob
$newRow = $newRow -Replace "`t|`n|`r",""
$newRow = $newRow -Replace " ;|; ",";"
$newRow += "`n"
#$newRow | Out-File $file
#[io.file]::WriteAllText("C:\zabbix\script\test.txt",$newRow)
Write-Host $newRow
$newRow | Export-Csv -Path $file -Append -noType
break
}
#cls
Write-Host $fileContent
CSV headers:
JobID,Result,RunStatus,IncludedSize,ExcludedSize,VmCount,Type,RunningJob
There is no point in using Export-Csv if you're building the CSV line by hand anyway.
Either change
$newRow | Export-Csv -Path $file -Append -noType -Force
into
$newRow | Add-Content $file
or build $newRow like this:
$newRow = New-Object -Type PSObject -Property #{
'JobID' = $var1
'Result' = $var2
'RunStatus' = $var3
'IncludedSize' = $var4
'ExcludedSize' = $var5
'VmCount' = $var6
'Type' = $var7
'RunningJob' = $var8
}
and the problem will disappear.
The reason for this behavior is that Export-Csv is for transforming objects into a tabular string representation of their properties. Essentially, an object
#{
propertyA: 'foo'
propertyB: 23
}
becomes
propertyA,propertyB
"foo","23"
If you're already building a string, the resulting (string) object has just a single property (Length), which doesn't match any of the properties from your existing CSV. Hence the error you're getting without -Force. Even if you use -Force, the properties written to the CSV are determined from the first item in the existing CSV. Properties that are not present in this set are omitted from the output, and properties from that set that are not present in the object are filled with null values.

Error while sending email through outlook in power shell script

I have a powershell script as below. Here I check whether any .err file has been created before 5 minutes and if yes, then I am sending an email for each error file with first 5 lines of the .err file.When I try to run the script I receive an email for the first file, but i get an error for the second file as shown in the snapshot below. I am new to powershell, and I am struggling to find any solution for this error.
$ChkFile = "D:\ErrorLog\*.err"
$ChkFilePath = "D:\ErrorLog"
$o = New-Object -comObject Outlook.Application
$mail = $o.CreateItem(0)
$mail.importance = 2
$mail.subject = “Error Log“
$mail.To = “email#email.com“
$FileExists = Test-Path $ChkFile
$FileCount = Get-ChildItem $ChkFilePath *.err | Measure-Object | %{$_.Count}
If ($FileExists -eq $True) {
If ($FileCount -gt 0)
{
Foreach($file in (Get-ChildItem $ChkFile))
{
Write-Host $file
$createtime = $file.LastWriteTime
$nowtime = get-date
if (($nowtime - $createtime).totalminutes -gt 5)
{
$GetFileContent = Get-Content $file -totalcount 5
$mail.body = $GetFileContent
Write-Host $GetFileContent
$mail.Send()
}
}
}
}
Error generated while executing the script:
After you invoke the $mail.Send() method you will likely need to recreate your mail object. You could do this by placing the object creation in the loop.
$ChkFile = "D:\ErrorLog\*.err"
$ChkFilePath = "D:\ErrorLog"
$o = New-Object -comObject Outlook.Application
$FileExists = Test-Path $ChkFile
$FileCount = Get-ChildItem $ChkFilePath *.err | Measure-Object | %{$_.Count}
If ($FileExists -eq $True) {
If ($FileCount -gt 0) {
Foreach($file in (Get-ChildItem $ChkFile)) {
Write-Host $file
$createtime = $file.LastWriteTime
$nowtime = get-date
if (($nowtime - $createtime).totalminutes -gt 5) {
$mail = $o.CreateItem(0)
$mail.importance = 2
$mail.subject = "Error Log"
$mail.To = "email#email.com"
$mail.importance = 2
$mail.subject = "Error Log"
$mail.To = "email#email.com"
$GetFileContent = Get-Content $file -totalcount 5
$mail.body = $GetFileContent
Write-Host $GetFileContent
$mail.Send()
}
}
}
}

Powershell to manipulate host file

I am looking at to see if I can create powershell script to update the contents in the host file.
Anybody know if there are any examples that manipulate the host file using powershell or any other scripting lanaguages?
Thanks.
All of these answers are pretty elaborate. This is all you need to add a hosts file entry:
Add-Content -Path $env:windir\System32\drivers\etc\hosts -Value "`n127.0.0.1`tlocalhost" -Force
IP address and hostname are separated by `t which is the PowerShell notation for a tab character.
`n is the PowerShell notation for a newline.
First up, if you're on Vista or Windows 7 make sure you run these commands from an elevated prompt:
# Uncomment lines with localhost on them:
$hostsPath = "$env:windir\System32\drivers\etc\hosts"
$hosts = get-content $hostsPath
$hosts = $hosts | Foreach {if ($_ -match '^\s*#\s*(.*?\d{1,3}.*?localhost.*)')
{$matches[1]} else {$_}}
$hosts | Out-File $hostsPath -enc ascii
# Comment lines with localhost on them:
$hosts = get-content $hostsPath
$hosts | Foreach {if ($_ -match '^\s*([^#].*?\d{1,3}.*?localhost.*)')
{"# " + $matches[1]} else {$_}} |
Out-File $hostsPath -enc ascii
Given this I think you can see how to use a regex to manipulate entries as necessary.
The Carbon module has a Set-HostsEntry function for setting a hosts entry:
Set-HostsEntry -IPAddress 10.2.3.4 -HostName 'myserver' -Description "myserver's IP address"
If anyone is looking for a more advanced example, I've always been particularly fond of this gist: https://gist.github.com/markembling/173887
#
# Powershell script for adding/removing/showing entries to the hosts file.
#
# Known limitations:
# - does not handle entries with comments afterwards ("<ip> <host> # comment")
#
$file = "C:\Windows\System32\drivers\etc\hosts"
function add-host([string]$filename, [string]$ip, [string]$hostname) {
remove-host $filename $hostname
$ip + "`t`t" + $hostname | Out-File -encoding ASCII -append $filename
}
function remove-host([string]$filename, [string]$hostname) {
$c = Get-Content $filename
$newLines = #()
foreach ($line in $c) {
$bits = [regex]::Split($line, "\t+")
if ($bits.count -eq 2) {
if ($bits[1] -ne $hostname) {
$newLines += $line
}
} else {
$newLines += $line
}
}
# Write file
Clear-Content $filename
foreach ($line in $newLines) {
$line | Out-File -encoding ASCII -append $filename
}
}
function print-hosts([string]$filename) {
$c = Get-Content $filename
foreach ($line in $c) {
$bits = [regex]::Split($line, "\t+")
if ($bits.count -eq 2) {
Write-Host $bits[0] `t`t $bits[1]
}
}
}
try {
if ($args[0] -eq "add") {
if ($args.count -lt 3) {
throw "Not enough arguments for add."
} else {
add-host $file $args[1] $args[2]
}
} elseif ($args[0] -eq "remove") {
if ($args.count -lt 2) {
throw "Not enough arguments for remove."
} else {
remove-host $file $args[1]
}
} elseif ($args[0] -eq "show") {
print-hosts $file
} else {
throw "Invalid operation '" + $args[0] + "' - must be one of 'add', 'remove', 'show'."
}
} catch {
Write-Host $error[0]
Write-Host "`nUsage: hosts add <ip> <hostname>`n hosts remove <hostname>`n hosts show"
}
Starting with Kevin Remisoski's excellent answer above, I came up with this which lets me add/update multiple entries at once. I also changed the regex in the split to look for any white space, not just tab.
function setHostEntries([hashtable] $entries) {
$hostsFile = "$env:windir\System32\drivers\etc\hosts"
$newLines = #()
$c = Get-Content -Path $hostsFile
foreach ($line in $c) {
$bits = [regex]::Split($line, "\s+")
if ($bits.count -eq 2) {
$match = $NULL
ForEach($entry in $entries.GetEnumerator()) {
if($bits[1] -eq $entry.Key) {
$newLines += ($entry.Value + ' ' + $entry.Key)
Write-Host Replacing HOSTS entry for $entry.Key
$match = $entry.Key
break
}
}
if($match -eq $NULL) {
$newLines += $line
} else {
$entries.Remove($match)
}
} else {
$newLines += $line
}
}
foreach($entry in $entries.GetEnumerator()) {
Write-Host Adding HOSTS entry for $entry.Key
$newLines += $entry.Value + ' ' + $entry.Key
}
Write-Host Saving $hostsFile
Clear-Content $hostsFile
foreach ($line in $newLines) {
$line | Out-File -encoding ASCII -append $hostsFile
}
}
$entries = #{
'aaa.foo.local' = "127.0.0.1"
'bbb.foo.local' = "127.0.0.1"
'ccc.foo.local' = "127.0.0.1"
};
setHostEntries($entries)
I have written a code to delete entries from host. You can easily change the code to add entries to it from the code.
$domainName = "www.abc.com"
$rplaceStr = ""
$rHost = "C:\Windows\System32\drivers\etc\hosts"
$items = Get-Content $rHost | Select-String $domainName
Write-host $items
foreach( $item in $items)
{
(Get-Content $rHost) -replace $item, $rplaceStr| Set-Content $rHost
}
For more information see
http://nisanthkv.blog.com/2012/06/13/remove-host-entries-using-powershell/
99% of the time admin rights are needed to modify a host record. Try adding this code at the top of your Powershell script.
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}
For me the biggest pain in dealing with the hosts file is remembering where it is. I set a variable that points to my hosts file in my PowerShell profile, which makes it easy to edit in a text editor.
In PowerShell, type the following to open your profile:
C:\> Notepad $profile
Add this:
$hosts = "$env:windir\System32\drivers\etc\hosts"
Save the file, then close and re-open PowerShell, running as administrator. You can't edit the hosts file without elevated permissions.
Now you can edit your hosts file the same way you'd edit your profile:
C:\> Notepad $hosts
I wrote a quick script that creates a simple GUI for adding new records to the HOSTS file. It will open a window, ask for hostname and IP, then append your input to the HOSTS file.
I'm sure it could be simplified and look cleaner... but works fine for my use case.
Enjoy!
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$hostsfilelocation = "$env:windir\System32\drivers\etc\hosts"
$readhostsfile = Get-Content $hostsfilelocation
$form = New-Object System.Windows.Forms.Form
$form.Text = 'Update HOSTS File'
$form.Size = New-Object System.Drawing.Size(300,200)
$form.StartPosition = 'CenterScreen'
$AddHosts = New-Object System.Windows.Forms.Button
$AddHosts.Location = New-Object System.Drawing.Point(55,120)
$AddHosts.Size = New-Object System.Drawing.Size(90,25)
$AddHosts.Text = 'Add Record'
$AddHosts.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $AddHosts
$form.Controls.Add($AddHosts)
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point(170,120)
$CancelButton.Size = New-Object System.Drawing.Size(75,25)
$CancelButton.Text = 'Cancel'
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $CancelButton
$form.Controls.Add($CancelButton)
$Hostslabel = New-Object System.Windows.Forms.Label
$Hostslabel.Location = New-Object System.Drawing.Point(10,20)
$Hostslabel.Size = New-Object System.Drawing.Size(280,20)
$Hostslabel.Text = 'Enter New HOSTNAME/FQDN:'
$form.Controls.Add($Hostslabel)
$HoststextBox = New-Object System.Windows.Forms.TextBox
$HoststextBox.Location = New-Object System.Drawing.Point(10,40)
$HoststextBox.Size = New-Object System.Drawing.Size(260,20)
$form.Controls.Add($HoststextBox)
$IPlabel = New-Object System.Windows.Forms.Label
$IPlabel.Location = New-Object System.Drawing.Point(10,60)
$IPlabel.Size = New-Object System.Drawing.Size(280,20)
$IPlabel.Text = 'Enter IP:'
$form.Controls.Add($IPlabel)
$IPtextBox = New-Object System.Windows.Forms.TextBox
$IPtextBox.Location = New-Object System.Drawing.Point(10,80)
$IPtextBox.Size = New-Object System.Drawing.Size(260,20)
$form.Controls.Add($IPtextBox)
$form.Topmost = $true
$form.Add_Shown({($HoststextBox,$IPtextbox).Select()})
$result = $form.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{
$inputhosts = $HoststextBox.Text
$inputip = $IPtextBox.Text
$newrecord = "$inputip $inputhosts"
Add-Content -Path $hostsfilelocation -Value $newrecord
}
This is the one I ended up using. I made an Active Directory group policy to run on every update, so if one of the entries is missing it is added, if it already exists you don't get a double entry:
function Test-FileLock {
param (
[parameter(Mandatory=$true)][string]$Path
)
$oFile = New-Object System.IO.FileInfo $Path
if ((Test-Path -Path $Path) -eq $false) {
return $false
}
try {
$oStream = $oFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)
if ($oStream) {
$oStream.Close()
}
return $false
} catch {
# file is locked by a process.
return $true
}
}
$hostsFile = "$($env:windir)\system32\Drivers\etc\hosts"
$hostsEntry = #('192.168.223.223 w2012', '192.168.223.224 w2019', '192.168.223.5 tbstorage', '192.168.223.7 tgcstorage','192.168.223.202 paneladmin.local.com')
foreach ($HostFileEntry in $hostsEntry)
{
While(Test-FileLock($hostsFile)) {
Write-Host "File locked! waiting 1 seconds."
Start-Sleep -s 1
}
# split the entry into separate variables
$ipAddress, $hostName = $HostFileEntry -split '\s+',2
# prepare the regex
$re = '(?m)^{0}[ ]+{1}' -f [Regex]::Escape($ipAddress), [Regex]::Escape($hostName)
# Write-Host $re
If ((Get-Content $hostsFile -Raw) -notmatch $re) {
Add-Content -Path $hostsFile -Value $HostFileEntry
Write-Host "Writing $HostFileEntry"
}
}
I have checked the entry if exists or not before write-in the host file.
$domainCheck = "installer.example.com"
$rHost = "C:\Windows\System32\drivers\etc\hosts"
$domainName = "`n8.8.8.8`tinstaller.example.com"
if((Get-Content $rHost | Select-String $domainCheck ).length -eq 0){
Add-Content -Path $rHost -Value $domainName -Force
}
#Kevin Remisoski's answer was nice but I wanted to be able to Add, Remove and Find (so I could determine if the host was in the set before trying to remove or add)
Simplified hosts.ps1:
# Original file - https://gist.github.com/markembling/173887
$DefaultHostsFilePath = "C:\Windows\System32\drivers\etc\hosts"
Function Add-Host([string]$Ip, [string]$HostName, [string]$HostsFilePath = $DefaultHostsFilePath) {
Remove-Host $HostsFilePath $HostsFilePath
$Ip + "`t`t" + $HostName | Out-File -Encoding ASCII -Append $HostsFilePath
}
Function Remove-Host([string]$HostName, [string]$HostsFilePath = $DefaultHostsFilePath) {
$Content = Get-Content $HostsFilePath
$NewLines = #()
foreach ($Line in $Content) {
$Bits = [regex]::Split($Line, "\t+")
if ($Bits.Count -eq 2) {
if ($Bits[1] -ne $HostName) {
$NewLines += $Line
}
} else {
$NewLines += $Line
}
}
# Write file
Clear-Content $HostsFilePath
foreach ($Line in $NewLines) {
$Line | Out-File -Encoding ASCII -Append $HostsFilePath
}
}
Function Get-Hosts([string]$HostsFilePath = $DefaultHostsFilePath) {
$Content = Get-Content $HostsFilePath
$Result = #()
foreach ($Line in $Content) {
$Bits = [regex]::Split($Line, "\t+")
if ($Bits.Count -eq 2) {
$Result += "$Bits[0] `t`t $Bits[1]"
}
}
return $Result;
}
Function Find-Host([string]$Pattern, [string]$HostsFilePath = $DefaultHostsFilePath) {
$Hosts = Get-Hosts $HostsFilePath;
$Filtered = ($Hosts | Select-String $Pattern)
return $Filtered
}
Example usage script:
. ".\hosts.ps1"
if ((Find-Host "MyNewEntry").Count -eq 0)
{
Add-Host "127.0.0.1:5000" "MyNewEntry"
Write-Host "Added Entry"
}
else
{
Remove-Host "MyNewEntry"
Write-Host "Removed Entry"
}
Write-Host "-- Begin Printing Hosts --"
Get-Hosts | Write-Host
Write-Host "-- End Printing Hosts --"
Best Solution!
if(!((Select-String -Path $env:windir\System32\drivers\etc\hosts -Pattern "localhost") -ne $null)){
Add-Content -Path $env:windir\System32\drivers\etc\hosts -Value "`n127.0.0.1`tlocalhost" -Force
}