Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ahmadalli/386da39e4c5db3f8999e170d1b50783f to your computer and use it in GitHub Desktop.
Save ahmadalli/386da39e4c5db3f8999e170d1b50783f to your computer and use it in GitHub Desktop.
How to reformat all C# files in a solution, in Visual Studio
# How to reformat all C# files in a solution, in Visual Studio 2012.
#
# Open Tools->Library Package Manager->Package Manager Console, and run the
# command below. At the end, all documents will be open in the IDE. (Low-RAM
# machines will have problems with large solutions.) Changed files will be
# modified in the IDE, and not saved to disk. You can SaveAll, then Close All
# if you're ready.
#
# VS2012 removed the VB-like macro language that existed in previous version of
# Visual Studio. However, the underlying DTE interface is still there, and you
# can reach it via PowerShell, in the Package Manager Console
#
# The weird GUID passed to [ProjectItem.Open](http://msdn.microsoft.com/en-us/library/envdte.projectitem.open.aspx)
# is [Constants.vsViewKindCode](http://msdn.microsoft.com/en-us/library/envdte.constants.vsviewkindcode.aspx).
#
# Normally I'd split this in to multiple lines, but the Package Manager Console
# doesn't support line continuation.
function f($projectItems) { $projectItems | ? { $_.Name -ne $null -and $_.Name.EndsWith( ".cs" ) -and -not $_.Name.EndsWith( ".Designer.cs" ) -and -not $_.Name.EndsWith( ".tt.cs" ) } | % { $win = $_.Open('{7651A701-06E5-11D1-8EBD-00A0C90F26EA}') ; $win.Activate() ; $DTE.ExecuteCommand('Edit.FormatDocument') ; } ; if ($projectItems) { $projectItems | % { f($_.projectItems) } } }
$dte.Solution.Projects | % { f($_.ProjectItems) }
#another version from https://gist.github.com/Haacked/984353 this one will also sort and remove usings and save and close window
#so it's better for big projects and low memmory machines.
function f($projectItems){$projectItems | ForEach-Object {$_.ProjectItems | ForEach-Object { if ($_.Name -ne $null -and $_.Name.EndsWith( ".cs" ) -and -not $_.Name.EndsWith( ".Designer.cs" ) -and -not $_.Name.EndsWith( ".tt.cs" )) {$window = $_.Open('{7651A701-06E5-11D1-8EBD-00A0C90F26EA}'); if ($window){Write-Host $_.Name;[System.Threading.Thread]::Sleep(100);$window.Activate();$_.Document.DTE.ExecuteCommand('Edit.FormatDocument');$_.Document.DTE.ExecuteCommand('Edit.RemoveAndSort');$window.Close(1);}} }}; if ($projectItems){ $projectItems | % { f($_.projectItems) } } }
$dte.Solution.Projects | % { f($_.ProjectItems) }
@ahmadalli
Copy link
Author

small change to exclude generated tt.cs files

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