Formatting - at once - all the files in a Visual Studio project

后端 未结 6 1326
小蘑菇
小蘑菇 2020-12-04 15:29

I am interested in formatting all the files in a Visual Studio (ver. 2005) project all at once.

Currently, there is a way to format a single document by doing somet

6条回答
  •  鱼传尺愫
    2020-12-04 15:54

    Additional step needed for Visual Studio 2015

    Phil Haack's solution posted by ANeves is perfect, but for some reason $item.FileCodeModel.Language always returns null in Visual Studio 2015 making the Format-Document skip all files and effectively do nothing.

    To (hackily) work around this limitation you can replace the Get-Language function:

    # Convert language guid to friendly name
    function Get-Language($item) {
        if(!$item.FileCodeModel) {
            return $null
        }
    
        $kind = $item.FileCodeModel.Language
        switch($kind) {
            '{B5E9BD34-6D3E-4B5D-925E-8A43B79820B4}' { 'C#' }
            '{B5E9BD33-6D3E-4B5D-925E-8A43B79820B4}' { 'VB' }
            default { $kind }
        }
    }
    

    with the following variant that uses the file's extension instead of the Language GUID:

    # Convert file extension to friendly language name
    function Get-Language($item) {
       if(!$item.FileCodeModel) {
           return $null
       }
    
       $filename = $item.Name
       $ext = $filename.substring($filename.lastindexof('.'),
                                  ($filename.length - $filename.lastindexof('.')))
       switch($ext) {
           '.cs' { 'C#' }
           '.vb' { 'VB' }
           # If you want to prevent re-formatting files that are not VB or C# source files 
           # (e.g. XML files in your project etc.), replace the following line with 
           # "default { $null }" (thanks to HHenn for this suggestion!)
           default { $ext }
       }            
    }
    

提交回复
热议问题