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
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]


getFileFragments "c:\boot.ini"


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. said...

It seems WMI has a class/object for this:

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