September 3, 2014 at 8:31 pm
Hi Experts,
can you please give a query that will give me a file name and date modified from a directory into a sql table
basically what we need is a query that will allow me to provide a directory and a variable for number of days for instance 1 day old and I want to be able to able to delete all files older than that date and of course I want to be able exclude files of a particular type where I would give it a wild card statement for example say i wanted to save all csv files i would have the wild card say <> '%.csv'
Thanks!
September 3, 2014 at 9:28 pm
I have written the query . Need to take care of few things as per requirement.
DECLARE @PathName VARCHAR(256)='E:\abcd\' ,
@CMD VARCHAR(512)
IF OBJECT_ID('tempdb..#CommandShell') IS NOT NULL
DROP TABLE #CommandShell
CREATE TABLE #CommandShell ( Line VARCHAR(512))
SET @CMD = 'DIR ' + @PathName + ' /TC'
PRINT @CMD -- test & debug
-- DIR F:\data\download\microsoft /TC
-- MSSQL insert exec - insert table from stored procedure execution
INSERT INTO #CommandShell
EXEC MASTER..xp_cmdshell @CMD
-- Delete lines not containing filename
DELETE
FROM #CommandShell
WHERE Line NOT LIKE '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9] %'
OR Line LIKE '%<DIR>%'
OR Line is null
SELECT
Line File_details
,LEFT(Line,20) AS file_date
,Rtrim(LTRIM(substring(Line,21,18))) as file_size
,Rtrim(LTRIM(substring(Line,39,Len(Line)))) as file_Names
from #CommandShell
September 4, 2014 at 11:28 am
unless there is another reason for loading the results into a sql database, to accomplish what you want you could just use powershell.
$path = "c:\temp\directory"
$nodays = "-1"
$excludes = "*.csv, *.doc"
get-childitem $path -file -exclude $excludes | where {$_.Lastwritetime -le (get-date).adddays($nodays} |remove-item
this will remove all files except csv and docs older than 1 day from c:\temp\directory
September 4, 2014 at 4:52 pm
Please, everyone... remember that there is such a thing as "DOS INJECTION". Take the appropriate safeguards and delouse the inputs.
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply