With previous versions of Visual Studio, I used Kevin Pilch-Bisson\'s script to format all C# files in my solution.
VS2012 dropped macro support, so that doesn\'t work a
Here's an update to the existing script which works on very large solutions.
It opens each file, formats it, then saves and closes the file rather than leaving it open. It also skips ".designer." files, since these should generally be left alone.
In recent versions of Visual Studio (after 2017), copy the script to a ps1 file, then in the Package Manager Console run . C:\path\to\the.ps1
to invoke it.
(It works in Visual Studio 2012 and 2013 to copy and paste it directly into the Package Manager Console.)
BE WARNED: Pasting this code into your console will immediately open and format every C# file in your entire solution, saving each modified file without asking. It might be a good idea to branch first...
function FormatItems($projectItems) {
$projectItems |
% {
# Write-Host " Examining item: $($_.Name)";
if ($_.Name -and $_.Name.ToLower().EndsWith(".cs") `
-and (-not $_.Name.ToLower().Contains(".designer."))) {
$win = $_.Open('{7651A701-06E5-11D1-8EBD-00A0C90F26EA}');
$win.Activate();
$dte.ExecuteCommand('Edit.FormatDocument');
if (!$_.Saved) {
Write-Host " Saving modified file: $($_.Name)";
$dte.ExecuteCommand('File.SaveSelectedItems');
}
$dte.ExecuteCommand('Window.CloseDocumentWindow');
}
if ($_.ProjectItems -and ($_.ProjectItems.Count -gt 0)) {
# Write-Host " Opening sub-items of $($_.Name)";
FormatItems($_.ProjectItems);
}
};
}
$dte.Solution.Projects | % {
Write-Host "-- Project: $($_.Name)";
FormatItems($_.ProjectItems)
}
;