Get free disk space in SAS on Windows

This SAS macro retrieves the amount of free disk space, and puts the value in the SAS log and in a global macro variable. It works with local and remote drives and mapped and UNC paths. To avoid data loss, use it as a sanity check to verify there is a reasonable amount of disk space before writing data.

%macro windows_bytes_free(sm_path);
%global mv_bytes_free;
/* In case of error */
%let mv_bytes_free = -1;
/* Run the DIR command and retrieve results using an unnamed pipe */
filename tempdir pipe "dir /-c  ""&sm_path""  | find ""bytes free"" " ;
data _null_;
    infile tempdir length=reclen ;
    input line $varying1024. reclen ;
    /* Parse the output of DIR using a Perl regular expression */
    re = prxparse('/([0-9]+) bytes/');
    if prxmatch(re, line) then do;
        bytes_str = prxposn(re, 1, line);
        bytes = input(bytes_str, 20.);
        /* Assign available disk space in bytes to a global macro variable */
        call symput('mv_bytes_free', bytes);
        kb = bytes /1024;
        mb = kb / 1024;
        gb = mb / 1024;
        format bytes comma20.0;
        format kb mb gb comma20.1;
        /* Write a note to the SAS log */
        put "NOTE: &sm_path " bytes= kb= mb= gb=;
    end;
run;
%if &mv_bytes_free eq -1 %then %put ERROR: error in windows_bytes_free macro;
%mend;
 
/* example of use */
* C: drive;
%windows_bytes_free(c:);
%put mv_bytes_free &mv_bytes_free;
 
* UNC path;
%windows_bytes_free(\\server\folder);
%put mv_bytes_free &mv_bytes_free;
 
* WORK library, because sometimes WORK is not on C:;
%windows_bytes_free(%sysfunc(getoption(work)));
%put mv_bytes_free &mv_bytes_free;

Tested with SAS 9.3 on Windows 7 64-bit (US English).

Updated 8/9/2013 to handle spaces in the path name. Added example showing how to find location of WORK library. */

2 thoughts on “Get free disk space in SAS on Windows

  1. i tried the above code, to check my Library space, encountering with error: error in windows_bytes_free macro.

    Could you please help me on this.

Leave a comment