Author Posts

May 22, 2017 at 6:59 am


I'm new to Powershell and I have just started using datatables.

How do I clean them up (Destroy) datatables after I've finished with them?

Below is my code...

I want to cleanup/destroy table after I have viewed it.



$sRegistoryLocations = “RegistoryLocations”

#Create RegistoryLocations Table object
$tRegistoryLocations = New-Object system.Data.DataTable “$sRegistoryLocations”

#Define Columns
$col1RegLoc = New-Object system.Data.DataColumn Path,([string])

#Add the Columns

#Enter path 1 to search.
$rowRegLoc = $tRegistoryLocations.NewRow()
$rowRegLoc.Path = “HKLM:\SOFTWARE\Wow6432Node\Microsoft\Office\Outlook\Addins”

#Enter path 2 to search.
$rowRegLoc = $tRegistoryLocations.NewRow()
$rowRegLoc.Path = “HKLM:\SOFTWARE\Wow6432Node\Microsoft\Office\Excel\Addins”

#Enter path 3 to search.
$rowRegLoc = $tRegistoryLocations.NewRow()
$rowRegLoc.Path = “HKLM:\SOFTWARE\Wow6432Node\Microsoft\Office\Word\Addins”

#Display the table
$tRegistoryLocations | format-table -AutoSize

#Now I want to destroy/clean up the datatable

May 22, 2017 at 11:43 am

Once your script finishes and the variables go out of scope, .NET will garbage collect them automatically.

May 22, 2017 at 12:40 pm

You can also use a

Remove-Variable -name 

to destroy them if you need them killed before the script ends..

David F.

May 22, 2017 at 11:58 pm

Choice... Thanks guys... I really appreciate the help.

Yeah I'm writing powershell code using the Powershell ISE.

If I create a table using the following method

# Create table
$dtPeople = New-Object System.Data.DataTable("people")
$cols = @("userlogin","username","managerlogin","managername","department")
# I then stick some data into it.

it doesn't seem to get garbage collected when the script ends. Because when I type at the command prompt in the Powershell ISE like the following I get...

PS C:\Windows\system32> $dvPeople

userlogin : TEST1
username : Test Guy1
managerlogin : mgr1
managername : Manager Guy1
department : IT

However if I call the I get the following message...

PS C:\Windows\system32> remove-Variable -$dvPeople
remove-Variable : Cannot find a variable with the name '-System.Data.DataRowView'.
At line:1 char:1
+ remove-Variable -$dvPeople
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (-System.Data.DataRowView:String) [Remove-Variable], ItemNotFoundException
+ FullyQualifiedErrorId : VariableNotFound,Microsoft.PowerShell.Commands.RemoveVariableCommand

So I'm not sure where I'm going wrong... The datatable appears to be there after the script has been run... But when I goto delete it it says it can't find it.

May 23, 2017 at 12:09 am

That's the ISE. it maintains scope; it's a development feature and is on purpose. Try it in the console.

May 23, 2017 at 12:11 am

And the $ is not part of the name.. you need to only use the name..

Remove-Variable -name dvPeople

David F.

May 23, 2017 at 12:24 am

You guys are awesome thanks heaps!