Reputation: 991
I have a list of users whose names start with the old naming convention which is first character and surname i.e ASmith, BJones, CGrayson etc and I need to remove the first character, so that I'm just left with surname, which I will then query AD with to extract first and lastname, however I was unable to rename the list. I tried this code, but can't see where I'm going wrong.
$name = get-content c:\tempfiles\list.txt
foreach ($name in $names)
{
$th = $name.substring(1);
rename-item $name -newname $th
} | export-csv C:\TempFiles\New.csv
Upvotes: 1
Views: 2159
Reputation: 23415
There's a typo in the first line of your code (you want the collection of names to go in to $names and then analyze each one in to the variable $name as part of your loop):
$names = get-content c:\tempfiles\list.txt
However in order for ForEach to support the pipeline you need to use ForEach-Object instead so the next section should be:
$names | ForEach-Object {
$th = $_.substring(1);
write-output $th
} | Set-content c:\tempfiles\newfile.txt
You also don't need to use Rename-Item, that's for renaming a file or other object retrieved via a namespace provider. Just output the new string with write-output and then use the pipeline to output it to a new text file.
If you want the result to go to a CSV file, and you want that file to also contain the old name, you could do something like this:
$names | ForEach-Object {
$Properties = [ordered]@{
'oldname' = $_
'newname' = $_.substring(1)
}
New-Object -Property $Properties -TypeName PSCustomObject
} | export-csv New.csv -NoTypeInformation
In this example we build a hashtable that has two properties (oldname and newname) and then create an object that has those properties which is then passed through the pipeline to export-csv.
Upvotes: 2