Skip to main content
Question

How to specify a username variable in the path for a file copy worklet

  • 23 July 2024
  • 3 replies
  • 43 views

For example, the file I am copying is a Word letterhead template that needs to go to:

 

C:\Users\tjm\AppData\Roaming\Microsoft\Templates

 

but I need to replace “tjm” with the logged in users’ username

3 replies

Badge

@John_Guarracino how would I enter the path into your scripts if I am trying to get to the users AppData folder, and each time its run it is a unique path to the folder?

 

For example C:\Users\xxx\AppData\Roaming\Microsoft\Templates where xxx is the current logged in user?

Userlevel 4
Badge

Hi Tommock,

Not a direct answer but I think this will get you close enough. I am using this code block to take a file and put it in all the users directories detected on the endpoint:
 

gci -name c:\users | foreach ($_) {
copy-item "txt-doc.txt" -Destination "C:\Users\$_\Desktop\special-folder\txt-doc.txt"
}

 The eval code of course is going to check for ‘txt-doc.txt’ in each directory before hitting the remediation code.

Regards,

Badge

Hi Tommock,

Not a direct answer but I think this will get you close enough. I am using this code block to take a file and put it in all the users directories detected on the endpoint:
 

gci -name c:\users | foreach ($_) {
copy-item "txt-doc.txt" -Destination "C:\Users\$_\Desktop\special-folder\txt-doc.txt"
}

 

While this may work there is a more ‘pure’ approach. 

 

Powershell Script
$EnabledUsers = Get-LocalUser | ForEach-Object {if ($_.Enabled -eq $true) {$_.Name}}
Write-Output $EnabledUsers

 

The command here fetches the names of all users, by default users Administrator, DefaultAccount, WDAGUtilityAccount will always reflect ‘False’. Guest will also reflect ‘False’ but can be enabled by the user. So if a machine has multiple users we can call in a loop 

 

Powershell Script

ForEach ($User in $EnabledUsers) {$FinalPath = "C:\Users\$($User.Name)\AppData\Roaming\Microsoft\Templates"
    Write-Output $FinalPath}

 

In the previous response, folders such as ‘Public’ which are available by default will also be looped in. Using the short command above can help avoid such errors.

 

In case it is a single machine, and you want to scale the command then just simply utilize environment variables to fetch the “users” path directly, regardless of device owner/username.

 

Powershell Script

$FullPath = “$env:USERPROFILE\AppData\Roaming\Microsoft\Templates”

Reply