Skip to content

Instantly share code, notes, and snippets.

@achingono
Last active November 8, 2018 22:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save achingono/63b702f7f0f07255c4f0b3ab503ec4c6 to your computer and use it in GitHub Desktop.
Save achingono/63b702f7f0f07255c4f0b3ab503ec4c6 to your computer and use it in GitHub Desktop.
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