• Writing a PowerShell script and kicking it off using powershell.exe from a SQL Agent CmdExec Job Step would be another option here. The backflips you're having to perform using xp_cmdshell to get directory listings into a table and then shell out using dynamic SQL and xp_cmdshell again all go away when you're in a PowerShell session. There is a little learning curve to getting started with PowerShell but it offers a much more robust bridge between the OS and SQL Server for these kinds of tasks than T-SQL does or ever will.

    There are no special teachers of virtue, because virtue is taught by the whole community.
    --Plato