Folder removal

Hi guys!

Simple one (i hope) I’m working on a script to automate the process of logging off then removing local user profiles from Remote Desktop Servers. I’ve fallen at the first hurdle and cannot get the script to delete a folder based on a variable - let me show you what i have

$c = Get-Credential 
$sessionhost = Read-Host "Please input session host"
$user = Read-Host "Please enter username"

Invoke-Command -Computer $sessionhost -ScriptBlock {Remove-Item $sessionhost\Users\$user -Credential $c }

When i use this format, it doesn’t seem to like the $user variable on remove-item. It ignores it and tries to delete everything inside “Users”.

How do i make sure it targets the username that i entered i the first read-host portion? Any help is greatly appreciated :smiley:

Unfortunately you can’t use local variables in the command scope. Local variables aren’t passed to the remote session, so you need to supply them explicitly when you run the command. Take a look here: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/invoke-command - under the -ArgumentList parameter.

Since you use all three variables in the remote script block, you need to update it as such:

Invoke-Command -Computer $sessionhost -ArgumentList $c,$sessionhost,$user -ScriptBlock {
  param($c, $sessionhost,$user)
  Remove-Item $sessionhost\Users\$user -Credential $c 
}

Note that the variables in param has to be in the same order as the ArgumentList, though the names doesn’t have to be the same, but it makes it easier.

If you are using powershell V3+, you can use the following syntax $Using:sessionhost / $Using:User / $Using:C

You can read more at this link:

There is a few group policy settings that delete profiles off the server automatically when the user logs off. If you enable these profiles should get deleted automatically.

https://www.petenetlive.com/KB/Article/0000602

Thank you so much for all your help guys! Much appreciated :smiley:

I will definitely learn more about using variables in scope and also that GPO!

So, i’ve got it working thanks to you lovely people - I’m developing it a bit further and need to add a bit of code that i haven’t had to use before, allow me to explain.

currently im deleting profiles from session hosts. As you may know, people can create multiple sessions and with that the profiles have “extensions” put onto the end of their original profile name, e.g

testuser can then next time be called testuser.001, testuser.SDC etc etc. Is there a way to include a wildcard so that i capture all of the variances?

My current line of code to remove is

Remove-Item -Path \\$sessionhosts\C$\Users\$user

What i was thinking is adding * after $user? Would that work?

The $user is defined by a read-host, which in 99% of cases will be their default username without any of the extras, this is why i want to be able to capture all variances :slight_smile: