question

Mrs_Fatherjack avatar image
Mrs_Fatherjack asked

Moving and renaming files using xp_cmdshell

I need to move and rename a file but for reasons I'm not going into can't use SSIS or DTS. I'm trying to use xp_cmdshell and getting the message "The syntax of the command is incorrect". I'm using examples I've found on line and am confused as to what I've done wrong. The rename should add the date onto the filename, for example EandWTest.txt should be moved to an archive folder and renamed EandWTest_0110523_16_07.txt. This is the code I've found and am trying to fit my needs, I'm not actually using the variables to stipulate the filename and path but will do that when I've got the basic code working: DECLARE @TodayDate as varchar(40), @TodayHour as varchar(40), @TodayMinu as varchar(40), @NewFileName as varchar(100), @cmdstr as varchar(128), @cmd VARCHAR(255), @sFileName AS VARCHAR(255), @sPath AS VARCHAR(255) SET @sFileName = 'EandWTest.txt' SET @sPath = 'C:\Auto Import\Auto Import\' SELECT @TodayDate = CONVERT(varchar(10), GETDATE(), 112) SELECT @TodayHour = DATEPART(hh,GETDATE()) SELECT @TodayMinu = DATEPART(mi,GETDATE()) SELECT @NewFileName = @sFileName + '_' + @TodayDate + '_' + @TodayHour + '_' + @TodayMinu + '.txt' print @NewFileName set @cmdstr='MOVE /Y C:\Auto Import\Auto Import\EandWTest.txt C:\Auto Import\Auto Import\Archive\' + @NewFileName print @cmdstr EXEC master..xp_cmdshell @cmdstr Many thanks.
sqlxp_cmdshellrenamemove
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
WilliamD avatar image
WilliamD answered
You are missing quotes around the path. You have spaces in the folder names and windows command line doesn't like that. Just put double quotes around the filenames to fix that. Also the value of @NewFileName is a bit messed up, just running the print command returned: MOVE /Y C:\Auto Import\Auto Import\EandWTest.txt C:\Auto Import\Auto Import\Archive\EandWTest.txt_20110523_17_13.txt So the .txt part at the end is not quite right. EDIT: So you want the command to end up looking like this: MOVE /Y "C:\Auto Import\Auto Import\EandWTest.txt" "C:\Auto Import\Auto Import\Archive\EAndWTest.200110523_17_13.txt"
2 comments
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Mrs_Fatherjack avatar image Mrs_Fatherjack commented ·
@WilliamD Awesome, that's fantastic many thanks.
0 Likes 0 ·
WilliamD avatar image WilliamD commented ·
You're welcome.
0 Likes 0 ·

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.