I'm working on a PowerShell script to rename directories, adding a specific set name and a digit at the start of each name. The directories in question look like this:
`123 - Descriptor`
`124 - Descriptor2 - 2 Variations`
After running my script, I want the directory names to change to:
`0123 - Set Name - Descriptor`
`0124 - Set Name - Descriptor2 - 2 Variations`
Currently, I have a script that uses `Get-ChildItem -Directory`, but I'm stuck on how to make it dynamic so that when I run `Add-SetName.ps1 -name 'Set Name 2'`, it replaces 'Set Name' with the variable instead. Right now, using variables seems to break the script. Any help would be appreciated!
3 Answers
Here's a more structured script that might help you out:
```powershell
[CmdletBinding()]
param (
[Parameter(Position=0,Mandatory=$true)]
[Alias("Path")]
[string]$BasePath,
[Parameter(Position=1,Mandatory=$true)]
[string]$SetName,
[switch]$WhatIf
)
$items = Get-ChildItem $BasePath -Directory
foreach ($item in $items) {
$num, $descriptor, $variations = $item.Name.Split('-') | ForEach-Object { $_.Trim() }
$newName = $num.PadLeft(4, '0') + " - " + $SetName + " - " + $descriptor + " - " + $variations
Rename-Item -Path $item.FullName -NewName $newName -WhatIf:$WhatIf
}
```
This way, you can run a dry run using `-WhatIf` to see the changes before applying them!
To get your script working with a variable for the set name, you just need to add a parameter block at the top of your script. Something like this:
```powershell
param(
[string]$name
)
```
Then replace 'Set Name' in your script with `$name`. This should allow you to call your script with `Add-SetName.ps1 -name 'SomeName'`. That will make it dynamic! Good luck!

I ran a test using `$name = 'Some Name'`, but it seems to still use `$name` literally instead of what I set it to. Ideally, it should be replacing it with 'Some Name', not '$name'. Has anyone else experienced this?