Skip to content

Instantly share code, notes, and snippets.

@Roemer
Forked from mikesigs/DeleteExcludedFiles.ps1
Last active August 9, 2021 15:26
Show Gist options
  • Select an option

  • Save Roemer/86b41e9f6ce32cc5c1981771fc6a7751 to your computer and use it in GitHub Desktop.

Select an option

Save Roemer/86b41e9f6ce32cc5c1981771fc6a7751 to your computer and use it in GitHub Desktop.
Allow also project files instead of only solutions, fix many bugs
<#
.SYNOPSIS
Find all files excluded from a Visual Studio solution or project with the option to delete the files.
.DESCRIPTION
Finds all excluded files in all projects in the provided Visual Studio solution or a specific project with the option to delete the files.
.PARAMETER File
The path to the .sln or .csproj file
.PARAMETER Delete
Delete the files directly from the disk
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$File,
[Parameter(Mandatory=$false)]
[switch]$Delete
)
$ErrorActionPreference = "Stop"
[Reflection.Assembly]::LoadWithPartialName('System.Web') | Out-Null
$projects = @()
if ($File.ToLower().EndsWith('.sln')) {
# Search a whole solution
$solutionDir = Split-Path $File | % { (Resolve-Path $_).Path }
$projects = Select-String -Path $File -Pattern 'Project.*"(?<file>.*\.csproj)".*' `
| % { $_.Matches[0].Groups[1].Value } `
| % { Resolve-Path(Join-Path $solutionDir ([System.Web.HttpUtility]::UrlDecode($_))) }
} else {
# Search a specific project
$projects = @((Resolve-Path $File))
}
#Write-Host ($projects -join "`n") # For Debugging
Write-Host "=== Processing" $projects.count "projects"
$excluded = $projects | % {
$projectDir = Split-Path $_
Write-Host (Split-Path $_ -Leaf)
$projectXml = [xml](Get-Content $_)
if ($projectXml.DocumentElement.Attributes['Sdk']) {
# New project type, skip
Write-Host "=> New project type, skipping"
return
}
$projectFiles = Select-String -Path $_ -Pattern '<(Compile|None|Content|EmbeddedResource|Resource|Page) Include="(.*)".*' `
| % { $_.Matches[0].Groups[2].Value } `
| % { Resolve-Path(Join-Path $projectDir ([System.Web.HttpUtility]::UrlDecode($_))) }
#Write-Host ($projectFiles -join "`n") # For Debugging
$diskFiles = Get-ChildItem -Path $projectDir -Recurse `
| ? { !$_.PSIsContainer } `
| % { $_.FullName } `
| ? { $_ -notmatch "\\obj\\|\\bin\\|\\logs\\|\.user$|\.*proj$|App_Configuration\\|App_Data\\" }
#Write-Host ($diskFiles -join "`n") # For Debugging
(compare-object $diskFiles $projectFiles -PassThru) | Where { $_.SideIndicator -eq '<=' }
}
Write-Host "=== Found" $excluded.count "excluded files"
if ($Delete)
{
Write-Host "Deleting excluded files from disk..."
$excluded | % { Write-Host $_; Remove-Item -Path $_ -Force}
}
else
{
Write-Host "Delete was not specified. Listing excluded files only..."
$excluded
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment