Private/Cs/CsFile/Edit-CsAddUsing.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<############################################################################
 # Add "using" line to end of "using" section in CS file
 # Just supply package name without "using" or ";"
 # Don't add if line already exists
 ############################################################################>

Function Edit-CsAddUsing([string]$csFile, [string]$packageName) 
{
    [string]$fullLine = "using $($packageName);"
    $contents = (Get-Content $csFile)

    if($contents | ?{$_ -match $fullLine}) {
        # already matches, skip it
    } else {
        [int]$lastLineWithUsing = -1
        [int]$index = 0
        foreach($line in $contents) {
            if($line -match "^using") {
                $lastLineWithUsing = $index
            } elseif($line -match "^[ \t]*$") {
                # ignore blanks
            } else {
                # something other than blank or using, we're done
                break
            }
            $index++
        }

        if($lastLineWithUsing -eq -1) {
            # No "using" at all, add to top
            $contents[0] = $fullLine + "`n" + $contents[0]
        } else {
            # Add after last "using"
            $contents[$lastLineWithUsing] = $contents[$lastLineWithUsing] + "`r`n" + $fullLine 
        }
        $contents | Set-Content $csFile
    }
}