Reputation: 1995
I want to copy a hosts file to c:\windows\system32\drivers\etc
via a powershell script but when I do, I get the below error. How can I run this command as admin without displaying the password?
Error I receive:
copy : Access to the path 'C:\Windows\System32\drivers\etc\hosts' is denied.
At line:1 char:1
+ copy z:\hosts C:\Windows\System32\drivers\etc
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (Z:\hosts:FileInfo) [Copy-Item], UnauthorizedAccessException
+ FullyQualifiedErrorId : CopyFileInfoItemUnauthorizedAccessError,Microsoft.PowerShell.Commands.CopyItemCommand
Command I run:
copy z:\hosts C:\Windows\System32\drivers\etc
Upvotes: 0
Views: 6793
Reputation: 37
The solution I used, is;
First I added a Self-Elevate to the script so that if it requires Administrator permissions, it will prompt the UAC(Corporate domain).
# Self-elevate the script if required
if (-Not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {
if ([int](Get-CimInstance -Class Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber) -ge 6000) {
$CommandLine = "-File `"" + $MyInvocation.MyCommand.Path + "`" " + $MyInvocation.UnboundArguments
Start-Process -FilePath PowerShell.exe -Verb Runas -ArgumentList $CommandLine
Exit
}
}
This will evaluate the commands you are running and open a new PowerShell Window in Administrator mode.
Here is where I found an example;
https://blog.expta.com/2017/03/how-to-self-elevate-powershell-script.html
Upvotes: 0
Reputation: 8741
From a PowerShell Session of a normal user (not -runAs), I use usually a single line copy like this, as I'm logged in as admin on my computer:
Start-Process PowerShell -Verb runAs -ArgumentList '-command Copy-Item -force z:\hosts C:\Windows\System32\drivers\etc'
Windows popups a confirmation, I then click on yes. If you want to avoid totally the popup Winddows, we must lower the system security level:
Search Bar\UAC\User Acount Control Parameters\Lower the slide at the lowest level.
This is a bad solution.
Upvotes: 0
Reputation: 1959
If you have administrator permissions, then you start PowerShell as administrator, or you can run the script as an administrator by adding,
Start-Process powershell -Verb runAs
Upvotes: 3