除了“echo.text>> file.txt”命令之外,如何将文本附加到文件

时间:2014-02-23 00:21:06

标签: batch-file cmd

我的批处理脚本中存在问题

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

如果%file%位于c:\windows\test.txt之类,那会让UAC抱怨

将显示提示

Access Denied
Success!

如何解决缓冲区输出未设置错误级别的问题? 我以为我可能会使用一些写入文本文件而不是>>的命令。 我可以使用Vista上面的Windows内置的任何命令,我不能使用其他CMD工具。

欢迎任何其他建议。我只需要附加文本并检查它是否已写入。

3 个答案:

答案 0 :(得分:1)

如果需要更多权限,这将中止,否则将继续。

@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

答案 1 :(得分: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

这是一种方法。我使用了一个名为q21962157.txt的文件进行测试。

将第一个attrib更改为+R以设置只读,-R以获得清除只读。 (我只是使用readonly属性来生成访问拒绝条件)

答案 2 :(得分:0)

也许如果您使用Powershell而不是Batch,您可能希望更好地集成到操作系统。也许这就是为什么Powershell会让您在运行脚本之前设置执行策略。