Delete local windows profile with PowerShell

2019-04-11 16:15发布

I am trying to write a script that will delete the local profile of a test account. I am using the following line to return the SID of any account that starts with "test-"

PowerShell: $UserSID = (Get-WmiObject Win32_UserProfile | Where {$_.LocalPath -like '*\test-*'}).SID

Once I had the SID I used wmic to do the deletion but, I am not sure how to translate that code into PowerShell.

WMIC:wmic /node:"localhost" path win32_UserProfile where Sid="%%b" Delete

5条回答
Luminary・发光体
2楼-- · 2019-04-11 16:35

I was thinking this would work, but I don't find a delete method on the Win32_UserProfile class

$UserSID = (Get-WmiObject Win32_UserProfile | Where {$_.LocalPath -like '*\test-*'}).SID
(gwmi -class Win32_UserProfile -filter "SID='$UserSID'").Delete()
查看更多
爷、活的狠高调
3楼-- · 2019-04-11 16:37

You can also just call the Delete method directly in a single statement:

(Get-WmiObject Win32_UserProfile | Where {$_.LocalPath -like '*\test-*'}).Delete()
查看更多
走好不送
4楼-- · 2019-04-11 16:43

Another reason of getting Exception calling "Delete" with "0" argument(s) is the user you're trying to delete is currently logged in. Log him off and try again.

查看更多
对你真心纯属浪费
5楼-- · 2019-04-11 16:56

I resolved this issue by opening Powershell as administrator (right click, Run as Administrator).

查看更多
小情绪 Triste *
6楼-- · 2019-04-11 17:02
Get-WmiObject Win32_UserProfile -Filter "RoamingConfigured = 'True'" | Remove-WmiObject

True - Roaming profile
False - Local Profile

查看更多
登录 后发表回答