How to Drop or Truncate Tables with Powershell?


###################### Drop Tables in Powershell #####################
# Example 1 - drop the tables in the MyTestDB database beginning with T
PS SQLSERVER:\SQL\Localhost\default\databases\mytestdb\tables> dir | ? {$_.Name -match "^T"} | %{$_.Name; $_.drop()}

# drop the tables in the MyTestDB database with 100001 or more rows

PS SQLSERVER:\SQL\Localhost\default\databases\mytestdb\tables>  dir | ? {$_.rowcount -gt 100000} | %{$_.Name; $_.drop()}


###################### Truncate Tables in Powershell #####################
# Let's say we want to truncate all tables in the dbo schema
# Step 1 - find them
PS SQLSERVER:\SQL\XU-ACER-PC\DEFAULT\Databases\MyTestDB\Tables> dir | ? {$_.Schema -eq "dbo"}

# Step 2- use the TruncateData method
PS SQLSERVER:\SQL\XU-ACER-PC\DEFAULT\Databases\MyTestDB\Tables> dir | ? {$_.Schema -eq "dbo"} | %{$_.TruncateData()}