I want to remove all user-created variables at the start of a script.
Currently I am doing Remove-Variable -Name * but it tries to dele
I would pull the list of existing variable names into an array at the beginning of the script, then remove any newly added variables at the end of the script:
### Start of script (store list of existing variable names)
$ExistingVariables = Get-Variable | Select-Object -ExpandProperty Name
<#
Script contents go here
#>
### End of script (remove new variables)
$NewVariables = Get-Variable | Select-Object -ExpandProperty Name | Where-Object {$ExistingVariables -notcontains $_ -and $_ -ne "ExistingVariables"}
if ($NewVariables)
{
Write-Host "Removing the following variables:`n`n$NewVariables"
Remove-Variable $NewVariables
}
else
{
Write-Host "No new variables to remove!"
}