Automatically finding missing and duplicate files in CSProj (Revisited)

Posted on Updated on

As promised in I have come back to the problem of detecting errors in Visual Studio project files. I have updated the script to now report CS files that are on disk that do not appear in the list of included (and compiled) files in the Project. This has a few limitations, including that it only works with CS files (although the script could be easily amended to look for any file extension you like).

Param(
  [string]$filePath = $(throw "You must supply a file path")
)

clear

"--- Working... ---"

$filePath = Resolve-Path $filePath

$xml = ([xml] ( gc $filePath ))

$dirPath = (split-path $filePath)

$filesIncluded = $xml.Project.ItemGroup.Compile `
| % {
    if ($_.Include -ne $null)
    {
        (resolve-path (join-path $dirPath $_.Include)).Path
    }
}

$filesOnDisk = gci -Path $dirPath -Include *.cs -Recurse | select -ExpandProperty FullName

$uniquePaths = $filesIncluded | select –unique

$duplicatePaths = Compare-object –referenceobject $uniquePaths –differenceobject $filesIncluded `
| select -ExpandProperty InputObject


$fileDiff = Compare-object –referenceobject $filesIncluded –differenceobject $filesOnDisk

$missingInCsProj = $fileDiff | ? { $_.sideIndicator -eq '=>' } | select -ExpandProperty inputObject
$missingOnDisk = $fileDiff | ? { $_.sideIndicator -eq '<=' } | select -ExpandProperty inputObject

# Just double check whether the files are really missing. They might not be
# cs files or they might be in another project
$missingOnDisk = foreach($path in $missingOnDisk)
{
    if(-not (test-path $path)){
        $path
    }
}

clear

if($missingOnDisk -or $duplicatePaths -or $missingInCsProj)
{
    if($missingOnDisk)
    {
        ""
        "---- Files in the CSProj missing from disk ----"
        $missingOnDisk
    }

    if($duplicatePaths)
    {
        ""
        "---- File paths appearing in the CSProj multiple times ----"
        $duplicatePaths
    }

    if($missingInCsProj)
    {
        ""
        "---- .CS files missing from the CSProj ----"
        $missingInCsProj
    }
}
else
{
    "=> No errors found in $filePath"
}

""

I am going to come back to this once more, to automatically fix the CsProj file rather than just reporting on errors.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s