0

I have a problematic part on my batch script

echo. Some text >> %file%
if %errorlevel%==0 echo Success!
if not %errorlevel%==0 echo Fail!

If %file% is somewhere like c:\windows\test.txt, that makes the UAC complain

The prompt will display

Access Denied
Success!

How can I work around this problems that the buffer output doesn't set an errorlevel? I thought that I may use some command that writes to a text file instead of >>. I can use any command that is built in to Windows above Vista, I can't use other CMD tools.

Any other suggestion is welcome. I just need to append text and check if it was written or not.

Andriy M
  • 76,112
  • 17
  • 94
  • 154
Vitim.us
  • 20,746
  • 15
  • 92
  • 109
  • The gist of the question suggests that your issue is same as [here](http://stackoverflow.com/questions/10354016/file-redirection-in-windows-and-errorlevel "File redirection in Windows and %errorlevel%"), even though your title makes it look like something different. Therefore, I'm voting to close your question as a duplicate of the one I've just linked. – Andriy M Feb 23 '14 at 21:15

3 Answers3

1

This will abort if more permissions are needed, otherwise it will continue.

@echo off
set "file=c:\windows\test.txt"
copy "%~f0" "%file%.~~~.tmp.~~~" >nul 2>&1
if errorlevel 1 echo no permissions - aborting&goto :EOF
del "%file%.~~~.tmp.~~~"
>>"%file%" echo(Some text
foxidrive
  • 40,353
  • 10
  • 53
  • 68
0
@ECHO OFF
SETLOCAL
:: make a tempfile
:maketemp
SET "tempfile=%temp%\%random%"
IF EXIST "%tempfile%*" (GOTO maketemp) ELSE (echo.something>"%tempfile%a")
ATTRIB +r q21962157.txt

copy q21962157.txt+"%tempfile%a" q21962157.txt >NUL 2>nul
ECHO ERRORLEVEL was %ERRORLEVEL%
IF ERRORLEVEL 1 (ECHO error - output text IN "%tempfile%a") ELSE (DEL "%tempfile%*")
ATTRIB -r q21962157.txt
GOTO :EOF

Here's a method. I used a file named q21962157.txt for my testing.

Change the first attrib to +R for set readonly, -R for clear readonly. (I'm just using the readonly attribute to generate an access-denied condition)

Magoo
  • 77,302
  • 8
  • 62
  • 84
0

Maybe if you used Powershell instead of Batch, you might expect better integration to the OS. Perhaps that is why Powershell makes you set Execution Policy before you run scripts.

djangofan
  • 28,471
  • 61
  • 196
  • 289