PowerShell: Delete files after a number of days

I used to do a lot of “batch commands” back in the good old MS-DOS days. As with everything, technology advances and PowerShell is nothing short of amazing. Support for PowerShell  commandlets seems to pop up all over the place and I use it more and more to complete tasks.

Let’s say that you want to delete files from a folder, recursively, that have a creation date before a specific number of days.  How would you do it?  That’s right - PowerShell.

$path  = 'F:\Program Files\Microsoft SQL Server\MSSQL12.SQLSERVER\MSSQL\Backup\Log'
$cutoffdays = (Get-Date).AddDays(-2)

Get-ChildItem $path -Recurse | ? {
  -not $_.PSIsContainer -and $_.CreationTime -lt $cutoffdays 
} | Remove-Item

You can even look for files that have a specific extension:

$path  = 'F:\Program Files\Microsoft SQL Server\MSSQL12.SQLSERVER\MSSQL\Backup\Log'
$cutoffdays = (Get-Date).AddDays(-2)
$extension = '.trn'

Get-ChildItem $path -Recurse | ? {
  -not $_.PSIsContainer -and $_.CreationTime -lt $cutoffdays -and $_.Extension -ieq $extension
} | Remove-Item

There are a number of other parameters and options. Give it a shot.

Microsoft Dynamics NAV: Create and Delete Directory dotNET Interop

The ability to extend the development library through dotNET Interoperability within the development environment of Microsoft Dynamics NAV really does open up things up. I have been asked on several occasions about creating directories  via Dynamics NAV code. Directories can easily be created and deleted through the use of the System.IO.Directory class.  The CreateDirectory method allows you to create all directories and subdirectories in the specified path.  This makes creating nested directories rather easy. The DeleteDirectory method also allows for the recursive removal of directories.

Text Constants:

Name ConstValue
DirectoryExistsErr Directory already exists.
DirectoryDoesNotExistErr Directory does not exist.
DirectoryCreatedMsg Directory %1 created.
DirectoryDeletededMsg Directory deleted.

Variables:

Name DataType Subtype
SystemIODirectory DotNet System.IO.Directory.'mscorlib'
SystemIODirectoryInfo DotNet System.IO.DirectoryInfo.'mscorlib'

Methods:

LOCAL CreateDirectory(path : Text;showconfirmation : Boolean) : Boolean
	IF SystemIODirectory.Exists(path) THEN
		ERROR(DirectoryExistsErr);
		
	SystemIODirectoryInfo := SystemIODirectory.CreateDirectory(path);
	IF showconfirmation THEN BEGIN
		MESSAGE(STRSUBSTNO(DirectoryCreatedMsg,SystemIODirectoryInfo.Name));
	END;

LOCAL DeleteDirectory(path : Text;recursive : Boolean;showconfirmation : Boolean)
	IF NOT SystemIODirectory.Exists(path) THEN
		ERROR(DirectoryDoesNotExistErr);
		
	SystemIODirectory.Delete(path, recursive);
	
	IF showconfirmation THEN BEGIN
		IF NOT SystemIODirectory.Exists(path) THEN
			MESSAGE(DirectoryDeletededMsg);
	END;

Use:

CreateDirectory('C:\temp\a\b',TRUE);
DeleteDirectory('C:\temp\a',TRUE,TRUE);

I have attached the sample codeunit Cod50051.txt (2.2KB)

Microsoft Dynamics NAV: Delete Remote FTP Files using dotNET Interop

In many data exchanges it is desired that a file be removed from the remote FTP server once it has been downloaded.  Building on the previous posts (List, Upload, Download) that extend FTP within Microsoft Dynamics NAV via dotNET Interop, the code listed below demonstrates how to remove a file via FTP. 

The local variables are declared as:

Name	DataType	Subtype
FtpWebRequest	DotNet	System.Net.FtpWebRequest.'System'
FtpWebResponse	DotNet	System.Net.FtpWebResponse.'System'
NetworkCredential	DotNet	System.Net.NetworkCredential.'System'

The function is declared as:

DeleteFile(siteaddress : Text[250];username : Text[80];password : Text[80];filename : Text[250])

FtpWebRequest := FtpWebRequest.Create(siteaddress + '/' + filename);
FtpWebRequest.Credentials := NetworkCredential.NetworkCredential(username, password);

FtpWebRequest.Method := 'DELE';
FtpWebRequest.KeepAlive := TRUE;
FtpWebRequest.UseBinary := TRUE;
//FtpWebRequest.UsePassive := FALSE;

FtpWebResponse := FtpWebRequest.GetResponse;

IF GUIALLOWED THEN BEGIN
  MESSAGE('%1 %2', FtpWebResponse.StatusCode, FtpWebResponse.StatusDescription);
END;

Microsoft Dynamics NAV: List FTP Files using dotNET Interop

This post continues the demonstration of extending the .NET Framework in Microsoft Dynamics NAV to transfer files via FTP.  We have already reviewed Uploading Files and Downloading Files via FTP from within Microsoft Dynamics NAV.   Another important part of exchanging files via FTP is the listing of files on the remote server.   The following code can be used to list the files on an FTP server.

The local variables are declared as:

Name	DataType	Subtype	
FtpWebRequest	DotNet	System.Net.FtpWebRequest.'System'	
FtpWebResponse	DotNet	System.Net.FtpWebResponse.'System'	
NetworkCredential	DotNet	System.Net.NetworkCredential.'System'	
Stream	DotNet	System.IO.Stream.'mscorlib'	
StreamReader	DotNet	System.IO.StreamReader.'mscorlib'

The function is declared as:

ListFiles(siteaddress : Text[250];username : Text[80];password : Text[80];filename : Text[250])

// If filename is not blank it will filter on the list
// For example this will retrieve all zip files
// ListFiles('ftp://10.1.10.67','username','password', '*.zip');

// For example this will retrieve all files
// ListFiles('ftp://10.1.10.67','username','password', '');


FtpWebRequest := FtpWebRequest.Create(siteaddress + '/' + filename);
FtpWebRequest.Credentials := NetworkCredential.NetworkCredential(username, password);

FtpWebRequest.Method := 'LIST';
FtpWebRequest.KeepAlive := TRUE;
FtpWebRequest.UseBinary := TRUE;
//FtpWebRequest.UsePassive := FALSE;

FtpWebResponse := FtpWebRequest.GetResponse;
Stream := FtpWebResponse.GetResponseStream;

StreamReader := StreamReader.StreamReader(Stream);

WHILE NOT (StreamReader.EndOfStream) DO BEGIN
  MESSAGE('%1', StreamReader.ReadLine);
END;

StreamReader.Close;
Stream.Close;

IF GUIALLOWED THEN BEGIN
  MESSAGE('%1 %2', FtpWebResponse.StatusCode, FtpWebResponse.StatusDescription);
END;


The data retrieved for each file in the code above will need to be further parsed to get the filename.

Having reviewed how to Upload a file with FTP, Download a file with FTP and Listing Files with FTP you can create something to perform  FTP client from within Dynamics NAV.

Do not forget to reference the FTPWebRequest Method string values.


Microsoft Dynamics NAV: Download with FTP using dotNET Interop

Having an extensive C# development background, as I had mentioned in a previous post, I was thrilled with the ability to access the .NET framework through the dotNET Interoperability introduced with the Microsoft Dynamics NAV Roletailored client.

When interfacing data with other systems it is often necessary to upload files via FTP. It may also be necessary to download files via FTP.  This can be accomplished directly in Microsoft Dynamics NAV via Interop.



The local variables defined:
Name	DataType	Subtype
FtpWebRequest	DotNet	System.Net.FtpWebRequest.'System'
FtpWebResponse	DotNet	System.Net.FtpWebResponse.'System'
NetworkCredential	DotNet	System.Net.NetworkCredential.'System'
Stream	DotNet	System.IO.Stream.'mscorlib'
SIOFile	DotNet	System.IO.File.'mscorlib'
StreamReader	DotNet	System.IO.StreamReader.'mscorlib'
MemoryStream	DotNet	System.IO.MemoryStream.'mscorlib'

The method to download the file from the remote site:

DownloadFile(siteaddress : Text[250];username : Text[80];password : Text[80];filename : Text[250];path : Text[250])

FtpWebRequest := FtpWebRequest.Create(siteaddress + '/' + filename);
FtpWebRequest.Credentials := NetworkCredential.NetworkCredential(username, password);

FtpWebRequest.Method := 'RETR';
FtpWebRequest.KeepAlive := TRUE;
FtpWebRequest.UseBinary := TRUE;
//FtpWebRequest.UsePassive := FALSE;

filename := path + filename;

FtpWebResponse := FtpWebRequest.GetResponse;
Stream := FtpWebResponse.GetResponseStream;

// Text files only
//StreamReader := StreamReader.StreamReader(Stream);
//SIOFile.WriteAllText(path + filename, StreamReader.ReadToEnd);

MemoryStream := MemoryStream.MemoryStream();
Stream.CopyTo(MemoryStream);
SIOFile.WriteAllBytes(filename, MemoryStream.GetBuffer());

Stream.Close;

IF GUIALLOWED THEN BEGIN
  MESSAGE('%1 %2', FtpWebResponse.StatusCode, FtpWebResponse.StatusDescription);
END;

Reading Stuff

Information in this document subject to change without notice.
All Software source code published is for demonstration and knowledge sharing purposes only. The Code is supplied "as is" without warranty as to result, performance or merchantability. Use at your own risk.
The opinions expressed herein are the opinions of the author and do not reflect those of any other entity.