Search code examples
windowspowershellget-wmiobject

Powershell Delete local user says not enough arguments


I'm writing a tool to make removing local copies of AD users from laptops, but once it gets to the delete step I get the below error:

Exception calling "Delete" with "0" argument(s): ""

The code related to it is this:

$UserProfile = Get-WmiObject Win32_UserProfile -filter "LocalPath Like 'C:\\users\\$str'"
$UserProfile.Delete()  

The $str variable is called a dozen lines before

Get-WMIObject -ClassName Win32_UserProfile -Filter "special=false and localpath like 'C:\\users\\%'" | ForEach-Object {
    #internal logic trimmed for brevity, it just check against a previous choice the user made and if it matches sets $target to the current object
    $target = $_    
}
$str = $target.localpath.TrimStart("C:\Users\")

This code should delete the local user folder and the registry value if I've read the man page for these functions correctly

The jist is that I get the WMI object, trim it to just the username as a string for display purposes, use that string to re-find the WMIobject and delete it

This really should work, but I get the above error, I get a similar error if I try to use the Remove-WMIObject function too. I know I'm redoing work since I already have the WMI Object in $target, but I did it like this cause the error didn't make sense.

Edit: The fix was to add -ComputerName localhost to the command pulling the WMI object (despite the command being able to fetch the relevant WMIobject as it previously was) Example code: $UserProfile = Get-WmiObject Win32_UserProfile -ComputerName localhost -filter "LocalPath Like 'C:\users\$str'"


Solution

  • The command needs an unspecified argument from the documentation that only the delete process needs: -ComputerName localhost

    Get-WmiObject Win32_UserProfile -ComputerName localhost -filter "LocalPath Like 'C:\users\$str'"