I have this bit of simple code where I am passed a variable for the username, I need to parse that and then use it in a path for a copy command. I have used outputting the variables to a text file to help try to troubleshoot the problem.
I parse the variable, and it seems to output to the text file properly, but when I use it in my path variable it shows as empty.
The Code:
param ([String] $mdmUserName)
$mdmUserName | Out-File "C:\Windows\Temp\test.txt"
$FullUserSplit = $mdmUserName.Split("\")
$FullUserSplit | Out-File -append "C:\Windows\Temp\test.txt"
$localusername = $FullUserSplit[2]
$localusername | Out-File -Append "C:\Windows\Temp\test.txt"
$from = "C:\Windows\Temp\Normaltest.dotm"
$to = "C:\Users\$localusername\AppData\Roaming\Microsoft\Templates\"
$to | Out-File -Append "C:\Windows\Temp\test.txt"
Copy-Item $from $to -Force
The output of the test.txt file:
Win11\User
Win11
User
C:\Users\\AppData\Roaming\Microsoft\Templates\
You can see that it outputs the $localusername variable correctly to the test.txt, but then when added to the path it is not there. I feel like I am missing something simple.
I also tried manually setting the $mdmusername manually to "Win11/User" with the same result.
CodePudding user response:
Arrays are zero based (they start with 0), thus: $FullUserSplit[1] or $FullUserSplit[-1] (which selects the last entry) – iRon
iRon's comment was the answer. I needed to use $FullUserSplit[1]
Outputting the $FullUserSplit to the troubleshooting file was throwing me off, as it outputted the full array on 2 lines.