Spaces are not allowed in other projects too: WPF, Forms. You can replace spaces with underscore, probably like this (in several places):
$itemName = $item.Name.Trim().Replace( " ", "_" )
Also make sure that the name contains only letters, digits, and underscore, and starts with letter or underscore.
Maybe you can also leave the Name of treeview item unassigned.