我编写了一个小的 powershell 脚本,如果它们存在,它会从 hosts 文件中删除一些条目。
就像现在一样,它会做它应该做的事情,如果条目存在,它会删除它。我添加了一些想法以确保脚本以管理员权限运行,因为没有提升的权限就无法更改文件。到目前为止,一切都很好。
但即使从非提升会话成功执行后,总会有一条不好玩的消息:
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
我正在使用的脚本附后:
# 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
此致
保罗