Using Powershell to update users home directory

I am trying to change the home directory path to a bunch of users.

I wrote a script in Ppowershell which should change the path the username like so:

\\serverName\shareName\$_.SamAccountName

The problem is that I get the DistinguishedName instead of the SamAccountName like so:

\\serverName\shareName\CN=UserName,OU=OuName,DC=domainName,dc=local

This is the script I wrote:

Get-ADUser -Filter * -SearchBase 'ou=XX,dc=domainName,dc=local' | ForEach-Object {
Set-ADUser $_.SamAccountName -HomeDrive "Z:" -HomeDirectory "\\serverName\shareName\$_.SamAccountName"
}

Can anyone see why this is not working?


Solution 1:

This is because of the way Powershell handles variables in quotes. Basically, rather than getting

$_.SamAccountName

You were actually getting

$_ + "SamAccountName"

To resolve this simply use the following method to encapsulate your variables:

Set-ADUser $_.SamAccountName -HomeDrive "Z:" -HomeDirectory "\\serverName\shareName\$($_.SamAccountName)"

Update: @JScott has informed me that this method is called a "subexpression"