Instantly share code, notes, and snippets.

Embed
What would you like to do?
Apply namespace to multiple C# files and associated aspx files using powershell
param(
[Parameter(Position=0,Mandatory=$true)]
[Alias("Path")]
$rootPath,
[Parameter(Position=1,Mandatory=$true)]
[Alias("Namespace")]
$rootNamespace
)
$namespacePattern = "namespace\s+([^\s]+)"
$classPattern = "(public\s+)?partial\s+class\s+([^\s]+)"
$files = Get-ChildItem $rootPath -Recurse -Include *.cs
#$table = @()
foreach ($file in $files)
{
$newNamespace = $file.FullName.Substring($rootPath.Length + 1)
$newNamespace = $newNamespace.Substring(0, $newNamespace.IndexOf(".")).Replace("\", ".").Replace(" ", "").Replace("_", "")
$newNamespace = [regex]::replace("${rootNamespace}.${newNamespace}", "\.([\w])(\w+)",{ ".$($args[0].Groups[1].Value.ToUpper())$($args[0].Groups[2].Value)" })
$newNamespace = $newNamespace.Substring(0, $newNamespace.LastIndexOf("."))
$newClassName = $file.Name.Substring(0, $file.Name.IndexOf("."))
$content = Get-Content -Path $file | Out-String
$match = $content | Select-String -Pattern $namespacePattern
$currentNamespace = ""
if ($null -ne $match.Matches)
{
$currentNamespace = $match.Matches[0].Groups[1]
$content -replace $namespacePattern,"namespace $newNamespace" `
-replace $classPattern,"public partial class $newClassName" `
| Set-Content -Path "${file}" -Encoding UTF8
}
else
{
$content -replace $classPattern,"namespace ${newNamespace}`r`n{`r`npublic partial class $newClassName" `
-replace "\}\s*\Z","}`r`n}" `
| Set-Content -Path "${file}" -Encoding UTF8
}
$aspx = "$($file.DirectoryName)\$($file.Name.Substring(0, $file.Name.LastIndexOf(".")))"
if (Test-Path -Path $aspx)
{
(Get-Content $aspx) -replace 'Inherits="([^"]+)"', ('Inherits="{0}.{1}"' -f $newNamespace,$newClassName) `
| Set-Content "${aspx}"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment