0

When I run this command

exec xp_cmdshell 'copy C:\---\cmdshell1\a23.txt C:\---\cmdshell2';

It copies a23.txt file from cmdshell1 to cmdshell2 folder.

When I run the same command second time it does not copy the same a23.txt file to folder cmdshell2 for second time. So after running xp_cmdshell command multiple times I only get one file in cmdshell2 which was generated the first time. My question is, how to write this command in order to copy the a23.txt file from cmdshell1 folder into cmdshell2 the amount of times I ran the query(if I have run the above query 3 times, I want to have 3 copies of a23.txt file in cmdshell2).

  • Do you get the results you want if you run that command outside of xp_cmdshell? – Erik Darling Sep 25 '18 at 18:27
  • Do you mean in basic Command Prompt @sp_BlitzErik? While running on Command prompt is asks whether to overwrite or not.. – Eola Giba Sep 25 '18 at 18:32
  • @EolaGiba - Is it ok to put a timestamp on each file in the target folder to make the files unique? – Scott Hodgin Sep 25 '18 at 18:36
  • Yes, @ScottHodgin – Eola Giba Sep 25 '18 at 18:37
  • That is the normal behavior of xp_cmdshell and just command shell. It will not create a new file if a file exists. You have to make them unique. Can you use powershell for this? Or call powershell.exe from your prompt? – Ali Razeghi Sep 25 '18 at 18:38
1

Here is an example of building a dynamic xp_cmdshell command that includes a timestamp on the file

declare @Cmd varchar(100)
set @Cmd = 'copy C:\test\a23.txt C:\test\a23-' + replace(replace(convert(varchar(19),sysdatetime()),' ','-'),':','-') + '.txt'
print @cmd
exec xp_cmdshell @cmd;
  • I prefer Scotts answer to mine but i'll leave my answer up in case it helps someone else in the future. Scotts answer doesn't require you to drop into powershell from xp_cmdshell while my solution does. – Ali Razeghi Sep 25 '18 at 19:00
0

That is the normal behavior of xp_cmdshell and just command shell. It will not create a new file if a file exists. You have to make them unique. This worked for me.

First create this script and put it in a folder, I use a scripts folder. I named it cptimestamps.ps1.

$src = "C:\cmdshell1\1.txt"; 
$date = Get-Date -Format yyyy-MM-dd-ms; 
$dst = "C:\cmdshell2\1-$($date).txt"; 
Copy-Item $src $dst

Then execute powershell.exe from cmd by using:

powershell.exe -command c:\scripts\cptimestamp.ps1

This worked fine for me. Make sure your powershell execution policy is set. In many environments people just do a set-exeuctionpolicy -executionpolicy Unrestricted

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.