Hi.
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.
Cheers,
Matt.
$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
$tRegistoryLocations.columns.add($col1RegLoc)
#Enter path 1 to search.
$rowRegLoc = $tRegistoryLocations.NewRow()
$rowRegLoc.Path = “HKLM:\SOFTWARE\Wow6432Node\Microsoft\Office\Outlook\Addins”
$tRegistoryLocations.Rows.Add($rowRegLoc)
#Enter path 2 to search.
$rowRegLoc = $tRegistoryLocations.NewRow()
$rowRegLoc.Path = “HKLM:\SOFTWARE\Wow6432Node\Microsoft\Office\Excel\Addins”
$tRegistoryLocations.Rows.Add($rowRegLoc)
#Enter path 3 to search.
$rowRegLoc = $tRegistoryLocations.NewRow()
$rowRegLoc.Path = “HKLM:\SOFTWARE\Wow6432Node\Microsoft\Office\Word\Addins”
$tRegistoryLocations.Rows.Add($rowRegLoc)
#Display the table
$tRegistoryLocations | format-table -AutoSize
#Now I want to destroy/clean up the datatable
donj
May 22, 2017, 6:13am
2
Once your script finishes and the variables go out of scope, .NET will garbage collect them automatically.
You can also use a
Remove-Variable -name <varname
to destroy them if you need them killed
before the script ends…
David F.
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.
donj
May 22, 2017, 6:39pm
5
That’s the ISE. it maintains scope; it’s a development feature and is on purpose. Try it in the console.
And the $ is not part of the name… you need to only use the name…
Remove-Variable -name dvPeople
David F.
You guys are awesome thanks heaps!