Powershell – icacls variable not working in powershell script

icaclspowershellwindows-nano-server

I am configuring a new fileserver running on nanoserver 2016 datacenter edition. Right now i am working on a powershell script to create user folders. But I get an error when using the icacls command to set permissions.

Enter-PSSession -Computername Test01 -Credential administrator

$Domain = "MYDOMAIN"
$user = Read-Host -Prompt 'Type in the username'
$UD = $Domain +"\"+ $user

E:\
mkdir e:\usernt\$user
mkdir e:\usernt\$user\temp
mkdir e:\usernt\$user\templates
mkdir e:\usernt\$user\lotus\notes
mkdir e:\usernt\$user\MyBar
copy c:\MyBar e:\usernt\$user\MyBar

New-SmbShare -Name $user$ -Path e:\usernt\$user
Grant-SmbShareAccess -Name $user$ -AccountName Everyone -AccessRight full

icacls e:\usernt\$user /T /C /grant '$UD:(OI)(CI)F' 

But it gives the following error:

 icacls : $UD: No mapping between account names and security IDs was done. 
 At line:1 char:1  
 + icacls e:\usernt\$user /T /C /grant '$UD:(OI)(CI)F'  
 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  
 + CategoryInfo          : NotSpecified: ($UD: No mapping...y IDs was done.:String) [], RemoteException  
 + FullyQualifiedErrorId : NativeCommandError  

When I change the code to the username (MYDOMAIN\t.test) instead of the variable ($UD) it works fine.

icacls e:\usernt\$user /T /C /grant 'MYDOMAIN\t.test:(OI)(CI)F' 

Also when I check the value of $UD it is set correctly to MYDOMAIN\t.test

Best Answer

To expand variables inside a string use double quotes not single ones.

icacls e:\usernt\$user /T /C /grant "$UD:(OI)(CI)F"