开发者

.bat script copy into System32 gives Access Denied

I'm writing a .bat script where I need to copy a file to System32. I change to the folder then attempt to copy the file from a storage folder to the System32 folder.

cd C:\Windows\System32
copy %~dp0file.txt file.txt

I get an error Access Denied, 0 files copied.

I see why this is a problem, because if I try to copy a file to System32 using the non-programmatic GUI interface, I get a prompt asking me to confirm. So with the scrip开发者_JAVA技巧t, how do I bypass this Windows permissions or set it correctly, or some other solution.

Edit: The hint I got from the answer below is that it's possible to trigger Windows to show its GUI prompt for the user to give permissions. This idea will do. Hopefully someone knows exactly how to do this.


Belongs on superuser (voting to move).

Answer is: use an elevated command prompt (or if you launch your batch file from a shortcut, select "Run as Admin" in the shortcut properties)

EDIT: Now that you explain you're looking for a programmatic way to trigger elevation, you should have a look at this other question (not necessarily the accepted answer, but all the other answers). I'd still vote to close, but as a dupe instead of move to superuser. From batch you might want to look at the "runas" command, but it will still need user confirmation.


You can use RunAs command to copy the file as a local administrator. http://ss64.com/nt/runas.html


I use this in all of my batch files to check admin permissions at the beginning of the batch file?

@echo off
goto permissionCheck

:permissionCheck
    echo Checking permissions...

    SET adminRights=0
    FOR /F %%i IN ('WHOAMI /PRIV /NH') DO (
        IF "%%i"=="SeTakeOwnershipPrivilege" SET adminRights=1
    )

    IF %adminRights% == 1 (
        echo Elevated permissions confirmed.

        pause >nul
    ) ELSE (
        echo Elevated permissions absent.
        echo.
        echo This file needs to be run as an Administrator.
        echo.
        echo Close this window, right-click on the file and click "Run as Administrator".
        echo   OR
        echo Log on to an Administrator account and run this file normally.

        pause >nul
    )

I'm aware that this solution doesn't enable you to copy to system32 without admin rights, but seeing as you need admin rights and there's no way around that I thought I would offer this solution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜