Need some advise (foreach and nested statements)

Hi everyone,

I am trying to put together a script that searches for users on an RDS host and if found, removes their user folder and deletes their registry key.

I have multiple RDS servers to check so i was going to use a loop to go through an array.

I am not sure what would be the best way to go about this, as in how to loop through on certain conditions etc…

Would i use a foreach loop, do while or do until? below is a outline of what im trying to achieve.

  1. Select first RDS host in the array
  2. Search host for username (username variable is input by user running the script)
  3. If the user is found on the host then attempt to remove user from RDS session and remove folder from C:\Users (if the user is not found then proceed with searching for user SID in registry and delete if found)
  4. Once folder is removed, search for SID and remove reg key if found
  5. Check folder and reg key are deleted, if so loop to next RDS host in the array.

For the array, i am using foreach ($RDSServer in $RDSServers)

I’m having issues with nested if statements within the foreach loop.

What way would be best to tackle this? any help/guidance is much appreciated.


This forum is for helping with problems with code and not for writing scripts. Please be sure to share any code you have already and ask specific questions. Make sure to format the code with the button ‘</>’.

A foreach loop is good for iterating through a set of objects which is what you have.

Welcome to the forum. :wave:t3:

If it’s about removing the user profile you may take a look at this blog post …

And in genereal … in the vast majorioty of the cases you’re not the very first one with a given task. So it is very likely that you can find code examples or even complete scripts and PowerShell modules online you can use right away you at least adapt to your particular needs with little effort. :wink: … there’s no need to re-invent the wheel again and again. :smirk:

That’s why you should use your prefered internet search engine to look for those code examples before you come to any forum to ask for help. :+1:t3: :love_you_gesture:t3: