Script to create datestamp folder causing issue

  • I am trying to create date stamp folder and later move files to that folder through following script.

    But when i execute script it create folder but as %folderdate% and not as datestamp.

    where as when i execute three of the commands through command prompt it works fine. So can anyone help me to sort out this and tell where iam going wrong.

    declare @setdate varchar (100)

    declare @CreateDir varchar (100)

    declare @Filemov varchar (100)

    select @setdate='set folderdate=%date:~0,2%-%date:~3,2%-%date:~6,4%'

    print @setdate

    select @CreateDir='mkdir G:\Testing\test1\%folderdate%'

    print @CreateDir

    select @Filemov='move /Y G:\Testing\*.csv G:\Testing\test1\%folderdate%'

    print @Filemov

    exec master..xp_cmdshell @setdate

    exec master..xp_cmdshell @CreateDir

    exec master..xp_cmdshell @Filemov

  • I think its due to the fact that each call to xp_cmdshell spawns a new shell process and so the second call (2nd process) can't see the variable. Which explains why its works in the cmd shell as one statement.

    You can try this, it works on my machine. Alter the path as required

    declare @setdate varchar (100)

    declare @CreateDir varchar (100)

    declare @Filemov varchar (100)

    --select @setdate='set folderdate=%date:~0,2%-%date:~3,2%-%date:~6,4%'

    select @setdate = convert(varchar(11),getdate(),105)

    print @setdate

    select @CreateDir='mkdir C:\Test\' + @setdate

    print @CreateDir

    select @Filemov='move /Y C:\Test\*.txt C:\Test\' + @setdate

    print @Filemov

    exec master..xp_cmdshell @CreateDir

    exec master..xp_cmdshell @Filemov

    Once you're happy you may want to specify with no output if you don't want it to interfere with a batch?

Viewing 2 posts - 1 through 1 (of 1 total)

You must be logged in to reply to this topic. Login to reply