I'm trying to update a list of directory names by adding a specific set name along with a digit at the beginning. Currently, my directories look like this:
`123 - Descriptor`
`124 - Descriptor2 - 2 Variations`
When I've finished, I want them to appear as:
`0123 - Set Name - Descriptor`
`0124 - Set Name - Descriptor2 - 2 Variations`
Here's what I have so far:
Get-ChildItem -Directory | where { $_.Name -match '(^[^-]*)-' } | Rename-Item -NewName { $_.Name -replace '(^[^-]*)-' , '0$1- Set Name -' }
The issue I'm facing is that I'd like to save this as a script called Add-SetName.ps1 and reference the set name from the command line, for instance by running `Add-SetName.ps1 -name 'Set Name 2'`. However, when I try to replace 'Set Name' with a variable parameter ($Set), it seems to break the script. Any guidance on how to properly implement this would be great!
2 Answers
Check this version of your script:
```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.basename -split '-' | ForEach-Object { $_.Trim() }
$newname = $num.PadLeft(4, '0') + " - " + $SetName + " - " + $descriptor + " - " + $variations
Rename-Item -Path $item.FullName -NewName $newname -WhatIf:$WhatIf
}
```
This version allows you to specify a base directory and does a dry run with the `-WhatIf` switch. Run it like `& Z:scriptingtest.ps1 -BasePath 'C:admintest-newtest' -SetName 'myset' -WhatIf`. Let me know if it works for your scenario!
For your script to accept a parameter for the set name, start your script with a param block:
```powershell
param($name)
```
Then, wherever you have 'Set Name' in your existing script, replace it with `$name`. For example: `-replace 'Set Name', $name`. Now, you should be able to call it like this: `Add-SetName.ps1 -name 'SomeName'` and it will work correctly!

I tried that and when I set `$name = 'Some Name'`, it seemed like it was still outputting the filename with `$name` instead of the actual value. I got something like `0123 - $Set - Descriptor`. How do I fix that?