I was not happy with the code I wrote in this post. The goal was to write my functions with a “generic” naming convention, and then “process them” – change the naming convention to match my employer’s company name. For example JBMURPHY-AD-GetCurrentSite would be “processed” to Company-AD-GetCurrentSite. In the previous post, I just looped thought and created an alias for each function that matched a RegEx.
I think figured out a better way. Instead of creating aliases, I read the contents of the script line by line, replacing strings as I go, and then create a new file with the new naming conventions.
First I created a hash table with my search and replace strings:
$SearchAndReplace = @{ "JBMURPHY-" = "COMPANY-"; "server.domain.com" = "realservername.company.com"; }
Next I loop through the files, get their content line by line, loop through the hash table replacing the matching text and output to a temp file.
foreach ($file in $(gci $SourcePath)) { $tempFile = [System.IO.Path]::GetTempFileName() get-content $file | %{ $OutPut=$_ ForEach ($key in $SearchAndReplace.Keys) { $OutPut=$OutPut -Replace $key,$SearchAndReplace[$key] } $OutPut >> $tempFile } move-item $tempFile $destination -force }
Much cleaner, and I can keep adding search and replace terms to my hash table.
Comments are closed.