powershell script – find orphaned C# files


I ran across a C# file that had been removed from its csproj file, but it hadn’t been deleted from version control.  So I wrote a script (Chris Sidi had already written one, though) to find the .cs files that weren’t in the “containing” .csproj file

 

param([string]$csproj = $(throw 'csproj file is required'))

$csproj = Resolve-Path $csproj
$dir = Split-Path $csproj

# get the files that are included in compilation
$xml = [xml](Get-Content $csproj)
$files_from_csproj = $xml.project.itemgroup | 
	%{ $_.Compile } | 
	%{ $_.Include } |
	?{ $_ } | 
	%{ Join-Path $dir $_ } |
	Sort-Object

# get the files from the dir
$files_from_dir = Get-ChildItem $dir -Recurse -Filter *.cs |
	%{ $_.FullName } |
	Sort-Object
	
Compare-Object $files_from_csproj $files_from_dir

Comments (3)

  1. onovotny says:

    If you’re using TFS, there’s also the TFPT Treeclean command which will do the same for an entire workspace.

  2. MSDNArchive says:

    This isn’t about finding files laying on disk that aren’t in source control.  For each of the files I found with this, they were in source control fine, but weren’t in any csproj files.  Since they weren’t actually being included in any projects, they were useless, so I went through each and "tf delete"-ed it, rebuilt to confirm, then checked in.