forked from brianary/scripts
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathRename-Script.ps1
61 lines (53 loc) · 2.15 KB
/
Rename-Script.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<#
.SYNOPSIS
Renames all instances of a script, and updates any usage of it.
.FUNCTIONALITY
Scripts
.LINK
Set-RegexReplace.ps1
.EXAMPLE
Rename-Script.ps1 Get-RomanNumeral.ps1 ConvertTo-RomanNumeral.ps1
Renames the script file, and searches other script files for references to it,
and updates them.
#>
#Requires -Version 3
[CmdletBinding(ConfirmImpact='High',SupportsShouldProcess=$true)] Param(
# The current name of the script to change.
[Parameter(Position=0,Mandatory=$true)][ValidateNotNullOrEmpty()][Alias('From')][string] $OldName,
# The desired name of the script to change to.
[Parameter(Position=1,Mandatory=$true)][ValidateNotNullOrEmpty()][Alias('To')][string] $NewName,
# Any directories within which to rename the script (and any usage).
[Parameter(Position=2,ValueFromRemainingArguments=$true)][ValidateNotNullOrEmpty()][Alias('Directory')]
[string[]] $ScriptDirectory = '.'
)
if($OldName -notlike '*.ps1') {$OldName += '.ps1'}
if($NewName -notlike '*.ps1') {$NewName += '.ps1'}
$i,$max = 0,(100/$ScriptDirectory.Length)
foreach($dir in $ScriptDirectory)
{
$oldPath = Join-Path $dir $OldName
Write-Progress "Renaming $OldName to $NewName" 'Finding script' -curr $dir -Percent ($i++/$max)
if(!(Test-Path $oldPath -Type Leaf) -or !$PSCmdlet.ShouldProcess($oldPath,"Rename to $NewName")) {continue}
Rename-Item $oldPath $NewName
}
Write-Progress "Renaming $OldName to $NewName" -Completed
Write-Progress "Updating uses of $OldName to $NewName" 'Finding uses'
$scope = $ScriptDirectory |ForEach-Object {"$_\*.ps1"}
[Microsoft.PowerShell.Commands.MatchInfo[]] $uses =
@(Select-String "\b$([regex]::Escape((Split-Path $OldName -LeafBase)))(?:\.ps1)?\b" $scope -List)
if($uses.Length -eq 0)
{
Write-Warning "No uses of $OldName found!"
}
else
{
$i,$max = 0,(100/$uses.Length)
foreach($use in $uses)
{
Write-Progress "Updating uses of $OldName to $NewName" "Updating script $($use.Path)" -curr $use.Line `
-Percent ($i++/$max)
if(!$PSCmdlet.ShouldProcess("$use","Update to $NewName")) {continue}
$use |Set-RegexReplace.ps1 $NewName
}
}
Write-Progress "Updating uses of $OldName to $NewName" -Completed