1

Someone on Stack Overflow shared the below PowerShell code. I have the code working in the script I modified. I'd like to add the Get-Module | Remove-Module; Clear-Host functions to it.

And would adding those actually help or have any ill effects after running the script?

I'm new on Stack Overflow and don't have the reputation to comment on the thread the code is found in. So I made a new question.

### Start of script (store list of existing variable names)
$ExistingVariables = Get-Variable | Select-Object -ExpandProperty Name
### 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!"
    }
briantist
  • 45,546
  • 6
  • 82
  • 127
  • 2
    Hi James! Welcome to SO. Could I ask what you're trying to achieve with the above code? If the PowerShell session ends, there will be no more variables at all. Or, if you're invoking a script (calling it by name, or using `&`, for example), rather than dot `.` sourcing it, it should be in its own (child) scope. Also, removing all imported modules could definitely have some ill effects (I recommend giving it a try). – briantist Aug 09 '21 at 02:38
  • What are you trying to accomplish? `Remove-Module` removes the modules from memory. – Abraham Zinala Aug 09 '21 at 03:04
  • Two things, one is I'm trying to run the script in question without exiting and restarting the PowerShell session. – James Johnson Aug 09 '21 at 17:49
  • The second thing is the script I added the code to does not delete a temp folder on exit, which it is supposed to. I was told maybe a variable or module in memory is locking that folder. – James Johnson Aug 09 '21 at 17:50
  • So you're trying to re-initialize PowerShell to a default state without closing and re-opening? [This answer might be what you're looking for there](https://stackoverflow.com/a/60592670/584676). – codewario Aug 09 '21 at 18:54
  • For the script not deleting a Temp folder, you should probably ask a separate question for that, or edit this question to focus on that specific issue. PowerShell generally isn't going to clean up stuff created in any of the TEMP directories on its own, that's something you'll have to implement. Modules may use their own TEMP files but that's also on them to clean up when appropriate as well. – codewario Aug 09 '21 at 18:56

0 Answers0