Powershell - "Clear-Item variable:" vs "Remove-Variable"

Graham Gold picture Graham Gold · Dec 8, 2012 · Viewed 60.2k times · Source

When storing text temporarily in powershell variables at runtime, what is the most efficient way of removing a variables contents from memory when no longer needed?

I've used both Clear-Item variable: and Remove-Variable but how quickly does something get removed from memory with the latter vs nulling the memory contents with the former?

EDIT: I should have made it a little clearer why I am asking.

I am automating RDP login for a bunch of application VMs (application doesn't run as a service, outsourced developers, long story).

So, I am developing (largely finished) a script to group launch sessions to each of the VMs.

Idea is that the script function that stores credentials uses read-host to prompt for hostname then get-credentials to pick up domain/user/password.

The pass is then converted from secure-string using 256-bit key (runtime key unique to machine/user that stored the creds and runs the group launch).

The VMs name, domain, user and encrypted pass are stored in a file. When launching a session, the details are read in, password decrypted, details passed to cmdkey.exe to store \generic:TERMSRV credential for that VM, clear plaintext pass variable, launch mstsc to that host, a few seconds later remove the credential from windows credential store. (If I passed password to cmdkey.exe as anything other than plaintext, the RDP session would either receive incorrect or no credentials).

So, hence the question, I need the password In plaintext to exist in memory for as short a time as possible.

To keep security guys happy, the script itself is aes256 encrypted and a c# wrapper with its own ps host reads, decrypts and runs the script, so there is no plaintext source on the machine that runs this. (Encrypted source on a file share so effectively I have a kill switch, can simply replace encrypted script with another displaying a message that this app has been disabled)

Answer

itmadez picture itmadez · Mar 2, 2016

The only way I have been able to, with certainty, to clear variable data/content is to remove all variables running in the current session using:

Remove-Variable -Name * -ErrorAction SilentlyContinue

This removes all variables immediately. In fact, I add this to the end of some of my scripts, so that I can be sure that running another script with potentially the same name, will not have new data added and cause undesired results.

DRAWBACK: If you only need one variable cleared, which was in my case a few minutes ago, then you need to re-instantiate input variables required by your script.