Technical Article

Delete all files from a folder using xp_cmdshell

,

Copy the script to SSMS.

Update the @Path value. Don't miss the back-slash at the end of the Path.

Run it.

declare@cmd varchar(100),
@Path varchar(200) ,
@FileName varchar(255)

select@Path = '\\Servername\Drive\D$\'  <--- Mention the PAth

declare@objFSO int
declare @i int
declare@File varchar(1000)

select @cmd = 'dir /B ' + @Path
create table #dir(files varchar(1000))

insert #dir exec master..xp_cmdshell @cmd

select * from #dir

while exists (select files from #dir where files is not null)
begin
select @filename = max(files) from #dir
--Print @filename 
select @File = @Path + @fileName
exec sp_OACreate 'Scripting.FileSystemObject', @objFSO out
exec sp_OAMethod @objFSO,'DeleteFile', null, @File
exec sp_OADestroy @objFSO 
delete from #dir where files = @filename
end

drop table #dir

Rate

5 (1)

You rated this post out of 5. Change rating

Share

Share

Rate

5 (1)

You rated this post out of 5. Change rating