Reputation: 11
I'm using this script to remove corrupted profiles from my RD servers the correct way. I'm wondering if I can make the script ask for the profile name to cleanup instead of typing it in the script manually.
Get-CimInstance -ComputerName servername1, servername2, servername3 -Class Win32_UserProfile |
Where-Object { $_.LocalPath.split('\')[-1] -eq 'profilenametocleanup' } |
Remove-CimInstance
The script works well and also removes corrupted registry items. I want our Servicedesk to use it so it would be great to make this more amateur friendly.
Thanks!
Upvotes: 1
Views: 4873
Reputation: 27423
The localpath won't always match exactly the username. Using the sid is more reliable. In fact, that object is indexed by the sid.
$user = 'admin'
$sid = Get-LocalUser $user | foreach { $_.sid.value }
get-wmiobject win32_userprofile | where sid -eq $sid | Remove-WmiObject -whatif
What if: Performing the operation "Remove-WmiObject" on target
"\\COMP001\root\cimv2:Win32_UserProfile.SID="S-2-6-31-4961843708-2576926490-3901110831-1002""
Upvotes: 0
Reputation: 174485
Absoutely! You just need to replace the variable value 'profilenametocleanup'
with a variable reference!
Variables in PowerShell are defined and assigned like this:
$username = "Some value or expression goes here"
To prompt the user to input a string value, we can use the Read-Host
cmdlet:
$username = Read-Host -Prompt "Enter the username of the profile to remove!"
Then, in the existing pipeline:
# replace the 'profiletocleanup' value with our variable instead
Get-CimInstance -ComputerName servername1, servername2, servername3 -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('')[-1] -eq $username } | Remove-CimInstance
If you might want to reuse this pipeline in a different script at a later point in time, it might be a good idea to rewrite it as a function:
function Remove-RemoteUserProfile
{
param(
[string]$Username,
[string[]]$ComputerName = @('servername1', 'servername2', 'servername3')
)
Get-CimInstance -ComputerName $ComputerName -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('')[-1] -eq $Username } | Remove-CimInstance
}
Now you can target any user or set of remote servers with the same command:
# Will remove user profile for user jdoe on servername1 through 3
Remove-RemoteUserProfile -User "jdoe"
# Will remove user profile for user jdoe on servername1 and a machine called client5
Remove-RemoteUserProfile -User "bob" -ComputerName servername1,client5
# In this example we prompt the user for the username before calling the function:
$username = Read-Host -Prompt "Enter the username of the profile to remove!"
Remove-RemoteUserProfile -User $username -ComputerName someOtherComputer123
Upvotes: 1