Search and delete file on all users with PowerShell

As mentioned in the previous blog post, as an IT Pro you are usually executing commands within the NT System\Administrator account, meaning you cannot delete files simply on the current logged in user. But fear not, we can fix this with the following PowerShell code:

$users = Get-ChildItem “Registry::HKEY_USERS” | Where-Object { $_.PSChildName -match ‘S-1-5-21-\d+-\d+-\d+-\d+$’ }

foreach ($user in $users) {
$userSID = $user.PSChildName
$appDataPath = “Registry::HKEY_USERS\$userSID\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders” | Get-ItemProperty -Name “AppData” | Select-Object -ExpandProperty “AppData”
$vlcPath = Join-Path $appDataPath “VLC”
$vlcrPath = Join-Path $vlcPath “test.txt”

if (Test-Path $vlcrPath) {
Write-Host “User SID: $userSID”
Write-Host “Found test.txt file in path: $vlcrPath”
Write-Host “Deleting test.txt file…”
Remove-Item -Path $vlcrPath -Force
Write-Host “test.txt file deleted.”
Write-Host “————————“


Let us assume that in %appdata%\VLC there is a file named test.txt. With the above script you can search on all users present on the machine if the above file exists and you can delete it. Change the location/file name as desired.

Leave a comment

Your email address will not be published. Required fields are marked *

two − two =