Thursday, January 25, 2007

Is my file fragmented?

Small function to determine if a file is fragmented - for instance to analyzed an .ldf/.mdf file.
The function below also demonstrates one way to invoke an external command/tool (in this case "contig.exe" from www.sysinternals.com).
The function requires contig.exe to be in the local path.

function getFileFragments {
    $filename = $args[0]
    $contigOutput = contig -a $filename
    foreach ($line in $contigOutput) {
        if ($line -match "Average fragmentation") {
            $splitline = $line.split(' ')
            $x = $splitline.count
            Write-Host $splitline[$x -2]
        }
    }
}

Usage:

getFileFragments "c:\boot.ini"

4 comments:

Anonymous said...

Good job! You found a solution to this. I remember seeing you ask in the PSH NNTP group...

Jakob Bindslet said...

Thanks Marco,

One alternative to the outlined function would be to use the xp_cmdshell in SQL to remotely analyse a given .mdf/.ldf file. This would of course require the xp_cmdshell extended stored procedure to be enabled on the SQL server.

EXEC xp_cmdshell "\\fileserver\fileshare\contig.exe -a localsqlfile.mdf"

At the moment I'm not sure which solution I'll use for my SQL management script.

marco.shaw said...

It seems WMI has a class/object for this:
http://outputredirection.blogspot.com/2007/07/hello-world.html

Anonymous said...
This comment has been removed by a blog administrator.