Skip to main content

Overview

The delenv action removes environment variables from local and remote systems using the Win32_Environment WMI class. This is essential for cleanup after operations and removing persistence markers.

Syntax

Parameters

Usage Examples

Operational Use Cases

Scenario 1: Cleanup After Operations

Scenario 2: Remove Command Output

SharpWMI automatically cleans up environment variables used for command output retrieval. Manual cleanup is only needed if operations fail or for custom variables.

Scenario 3: Remove Persistence Markers

Scenario 4: Batch Cleanup

User Context

The delenv action deletes variables in the user context. Variables must match both name and username to be deleted.
Variables are user-specific:
  • System variables require SYSTEM context
  • User variables are tied to specific username
  • Cannot delete other users’ variables without proper context

Remote vs Local Usage

Use for:
  • Local cleanup
  • Testing
  • Post-operation tidying

Detection Considerations

  • Win32_Environment class deletions
  • Event ID 5857: WMI activity
  • Sysmon Event ID 19-21: WMI operations
  • Environment variable removal
  • Registry deletions in environment key
  • HKCU\Environment changes
  • Event ID 4657: Registry value modification/deletion
  • Suspicious variable deletion
  • Bulk deletion operations
  • Deletion of recently created variables
  • Cleanup correlated with other activity

Best Practices

Always Clean Up

  • Remove variables after use
  • Don’t leave indicators
  • Clean up on operation failure
  • Automate cleanup in scripts

Verify Deletion

  • Confirm variable was deleted
  • Check with getenv action
  • Handle errors gracefully
  • Log cleanup operations

Operational Security

  • Clean up immediately after use
  • Don’t leave data in environment
  • Remove all custom variables
  • Check for orphaned variables

Error Handling

  • Handle variable not found
  • Verify admin privileges
  • Account for permission issues
  • Retry on failure

Cleanup Workflow

Complete cleanup example:

Troubleshooting

Cause: Variable doesn’t exist or wrong user contextSolution:
  • Verify variable exists with getenv
  • Check variable name spelling
  • Ensure correct user context
  • Variable may have been already deleted
Cause: Insufficient privilegesSolution:
  • Use username and password parameters
  • Verify admin rights on target
  • Check UAC remote restrictions
  • May need SYSTEM context for system variables
Cause: Trying to delete another user’s variableSolution:
  • Variables are user-specific
  • Must authenticate as that user
  • Or use SYSTEM context
  • Cannot delete other users’ variables directly

getenv

Retrieve environment variables

setenv

Set environment variables

query

Query Win32_Environment directly

exec

Execute cleanup commands

Alternative Methods

Verification

After deletion, verify the variable is gone: