Copy a File to a Folder in a User's Profile

  • 10 September 2020
  • 4 replies
  • 528 views

Userlevel 5

I generated this worklet for a customer that wanted to take a text file called “signin.slacktoken” with a Slack token in it and have it copied to users’ Download directory. For your purposes, upload the file you want to be copied and set the $uploadfile variable in the evaluation and remediation to be exactly equal to the name of the uploaded file. Then just set the location you want the file in evaluation and remediation.


Evaluation:


# Set variable to the exact name of the installation file uploaded
$uploadfile = 'signin.slacktoken'

# Sets current user
$currentusr = (Get-WmiObject -class win32_process -ComputerName 'localhost' | Where-Object name -Match explorer).getowner().user

# Check to see if the file exists in the user's profile location where it should be saved. If so, exit with no action.
if (Test-Path -Path "c:\Users\$currentusr\Downloads\$uploadfile") {
exit 0
} else { Exit 1 }

Remediation:


# Sets current user
$currentusr = (Get-WmiObject -class win32_process -ComputerName 'localhost' | Where-Object name -Match explorer).getowner().user

# Set variables to the exact name of the installation file uploaded & where to copy it
$uploadfile = "signin.slacktoken"
$uploadPath = "c:\Users\$currentusr\Downloads"

# If directory doesn't exist, create it
If (!(Test-Path $uploadPath)) {
New-Item -ItemType Directory -Path $uploadPath -Force
}

# Copy the installation file uploaded to the desired location in the user's profile. In this example it's the user's Downloads folder.
Copy-Item $uploadfile -Destination "$uploadPath\$uploadfile"

4 replies

Userlevel 2
Badge

Thanks I’ll give this a try

Badge

Works great for me as long as the folder exists. I found that if the folder you specified does not exist the script will attempt to create the folder, but something causes the folder to be created as a file instead. This causes the operation to fail.


I corrected this by adding the following just above the copy-item operation


New-Item -ItemType File -Path "c:\some\path\filename.ext" -Force
Userlevel 5

Thanks for your input. I tweaked my code to handle non-existant folders. I wrote it for a known existing folder so wasn’t considering that.

Badge

This worked great! Thanks so much!

Reply