Private/Cs/CsFile/Edit-CsAddUsing.ps1

<############################################################################
 # 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
    }
}