Reputation: 11
I've written a small powershell script which removes some entries from the hosts file if they exists.
As it is right now, it does what it should and removes the entry if it exists. I added some thinks to make sure, the script is run with admin-rights, because you cannot change the file without elevated rights. so far, so good.
But after successfully execution even from a non-elevated-session, there is always an unfunny message:
Out-File : Access to the path "C:\WINDOWS\system32\Drivers\etc\hosts" denied.
In C:\Users\student01\Documents\Schulung\Student\Student01\Remove_Training_Environment.ps1:36 Zeichen:5
+ Out-File "$($env:windir)\system32\Drivers\etc\hosts" -Force
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (:) [Out-File], UnauthorizedAccessException
+ FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand
The Script i am using is attached:
# Get the ID and security principal of the current user account
$progressPreference = 'silentlyContinue'
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
# Get the security principal for the Administrator role
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
# Check to see if we are currently running "as Administrator"
if ($myWindowsPrincipal.IsInRole($adminRole))
{
# We are running "as Administrator" - so change the title and background color to indicate this
$Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "Powershell CaptureTheFlag is starting"
$Host.UI.RawUI.BackgroundColor = "Black"
clear-host
}
else
{
# We are not running "as Administrator" - so relaunch as administrator
# Create a new process object that starts PowerShell
$newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
# Specify the current script path and name as a parameter
$newProcess.Arguments = $myInvocation.MyCommand.Definition;
# Indicate that the process should be elevated
$newProcess.Verb = "runas";
# Start the new process
[System.Diagnostics.Process]::Start($newProcess);
# Exit from the current, unelevated, process
exit
}
# Powershell-Script for the training: removing some environment-stuff
$progressPreference = 'silentlyContinue'
(Get-Content "$($env:windir)\system32\Drivers\etc\hosts") -replace ('^\s*8.8.8.8\s+www.test.com',' ') |
Out-File "$($env:windir)\system32\Drivers\etc\hosts" -Force
best regards
Paul
Upvotes: 1
Views: 733