sql-serverxp-cmdshell

xp_cmdshell write file directory to a text file


how do I write my file directory to a text file? The directory I want to use is C:\

The code I have now is

exec xp_cmdshell 'dir *.exe & echo > file_directory.txt';--

It's not writing to a file though. Do I need to say this...

exec xp_cmdshell 'cd c: \ & dir *.exe & echo > file_directory.txt';--

Solution

  • cd (by itself) only sets the working directory, it won't change the working disk drive. If you (may) need to change the working drive and working directory you need pushd c:\ or cd /d c:\.

    The easier solution is to fully-qualify the file name instead:

    echo > c:\file_directory.txt
    

    But it's generally not a good idea to write to the root of C:. Microsoft has tried to make this harder, for the very good reason that opening up write privilege to the root of your system partition opens up all sorts of security risks.

    (Update:) I think what you want is

    exec xp_cmdshell 'dir *.exe > c:\file_directory.txt';