-4

This is pretty weird. I have a simple batch script:

 @echo off
 @echo test> text.txt

When I run it without elevated permissions it creates "text.txt", which contains "test" inside it.

However when I run the same batch file WITH elevated permissions it does nothing. Why?

Ashen Frost
  • 321
  • 2
  • 3
  • How are you "running with elevated permissions?" Can you provide an example of what that step entails? This is key, I would think. – gravity Apr 04 '19 at 18:48
  • 2
    This is not true. I can redirect text to a file just as you have in either a standard or elevated run. (I just tested it to make sure nothing had changed in recent Windows updates on Win10.) What folder are you trying to write to without elevation? What folder with elevation? – Ken White Apr 04 '19 at 18:55
  • 5
    `test.txt` is definitely created, but not in directory of the batch file as you most likely expect on being run as administrator, but in `%SystemRoot%\System32`. Why? Read my answer on [Why does 'Run as administrator' change (sometimes) batch file's current directory?](https://stackoverflow.com/a/31655249/3074564) Solution: `@echo test>"%~dp0text.txt"`. `%~dp0` references drive and path of the batch file ending always with a backslash. – Mofi Apr 04 '19 at 19:08
  • @Mofi You're absolutely right, I don't know why I didn't think about this. I managed to solve the issue using the code you provided. Thanks so much for the reply! – Ashen Frost Apr 04 '19 at 21:18

2 Answers2

1

when you run in with elevated permissions, it cd to C:\WINDOWS\system32 so you need to cd earlier in your script

@echo off
cd C:\path\where\you\want\to\create\your\file
@echo test> text.txt

you can also do this if you want the file to be created in the folder the batch is in

@echo off
cd %~dp0
@echo test> text.txt
Matthijs
  • 2,483
  • 5
  • 22
  • 33
Mattlau04
  • 78
  • 1
  • 9
  • `C:\WINDOWS\system32` in first sentence is wrong because of Windows can be installed on any drive, not only on drive `C:`. The second line of first batch code would fail to change to specified directory on drive `C:` if Windows is installed for example on drive `D:`. The second line of second batch file fails and can be even harmful if the path to batch file contains the character `&` which is a valid character for a directory name. So I don't know why you posted this not good answer although the questioner replied already with issue solved with the simple command line posted by me in comment. – Mofi Apr 06 '19 at 18:02
0

Try this one

@echo off
echo.
cd N:\myfolder
N:
echo hi>>123.txt
AR Khan
  • 1
  • 5