Skip to content

Instantly share code, notes, and snippets.

@jwcarroll
Created February 26, 2013 14:09
Show Gist options
  • Save jwcarroll/5038661 to your computer and use it in GitHub Desktop.
Save jwcarroll/5038661 to your computer and use it in GitHub Desktop.
A powershell script that will exclude files in a project from StyleCop analysis.
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)]
[string]$projectPath,
[string]$filter='*.*',
[switch]$useRegularExpression=$False,
[switch]$undo=$False
)
$ErrorActionPreference = "Stop"
if(!(test-path (Resolve-Path $projectPath))){
throw "Unable to locate project file"
}
else{
$projectPath = Resolve-Path $projectPath
}
#Load the project file
$xml = New-Object XML
$xml.Load($projectPath)
#Update compiled files to add the <ExcludeFromStyleCop> element
$xml.GetElementsByTagName("Compile") |
where {
if($useRegularExpression){
$_.Include -match $filter
} else{
$_.Include -like $filter
}
} |% {
if($undo){
Write-Host "Undoing exlusion for file '$($_.Include)'" -ForegroundColor 'Gray'
if($_.ExcludeFromStyleCop){
$parent = $_
$items = @()
$_.GetElementsByTagName("ExcludeFromStyleCop") |% {
$items = $items + $_
}
$items |% {
$parent.RemoveChild($_) | Out-Null
}
}
} else{
Write-Host "Ignoring file '$($_.Include)'" -ForegroundColor 'Gray'
if($_.ExcludeFromStyleCop -eq $null){
$elem = $xml.CreateElement("ExcludeFromStyleCop", $xml.Project.NamespaceURI)
$elem.InnerText = "True"
$_.AppendChild($elem) | Out-Null
} else{
$_.GetElementsByTagName("ExcludeFromStyleCop") |% {
$_.InnerText = "True"
}
}
}
}
#Save File
$xml.Save($projectPath)
if($undo){
Write-Host "Project file has been updated. Exclusions matching '$filter' have been undone"
} else{
Write-Host "Project file has been updated to exclude all files matching '$filter' from StyleCop"
}
@jwcarroll
Copy link
Author

This script will allow you to exclude files in a project from StyleCop analysis by adding <ExcludeFromStyleCop>True</ExcludeFromStyleCop> for each <Compile> element that it matches.

To exclude all files

ExcludeProjectFromStyleCop.ps1 "c:\dev\awesome.csproj"

To exclude only files that match a filter

ExcludeProjectFromStyleCop.ps1 "c:\dev\awesome.csproj" "Admin*.cs"

To use a regular expression while filtering

ExcludeProjectFromStyleCop.ps1 "c:\dev\awesome.csproj" "Admin[0-9]{3}\.cs" -useRegularExpression

To undo changes

ExcludeProjectFromStyleCop.ps1 "c:\dev\awesome.csproj" -undo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment