Powershell Delete list of files from directories located on a network share

citrixcleanuppowershell

I wrote the following script to delete all temp files and cached data from users profiles located on network share.

It works fine when I run it locally on my machine but when I attempt to run it on a network share it always fails.

This is how my script works,

  1. specify a list of folder that needs cleanup names.text
  2. specify the path for the directory
  3. use remove-item command to delete the required files

     $userlist = Get-Content -Path "C:\Profiles\names.txt"
     $home_folders = "C:\Profiles\"
    
    
     $UserList | ForEach-Object {    
     $User_Home = $Home_Folders + "\" + $_
    
     Remove-Item "$User_Home\UPM_Profile\AppData\Local\Temp\*" -Force -Recurse 
    }   
    

What I have done so far?

  • I tried placing the path as \UNC path but that does nothing.
  • I tried to remove -erroraction silentlycontinue to see what kind of errors shows up but it does nothing. like I execute the script but it just hang.
  • I also tried to execute the script from the same network share but without luck.

Best Answer

You're currently appending two backslashes to your directory:

$home_folders = "C:\Profiles\"
#...
$User_Home = $Home_Folders + "\" + $_

You could get around this by removing the slash from home_folders ($home_folders = "C:\Profiles) or by removing it from your join ($User_Home = $Home_Folders + $_).

However a better way is to use the Join-Path cmdlet, which checks for a slash and appends one as needed:

$User_Home = Join-Path $Home_Folders $_