Introduction
In the past, DBAs use to work with VB scripts, but now the PowerShell is reducing a lot all the administrative tasks with this flexible, versatile shell. In another article, Shawn Melton shows us the PowerShell basics. This article will show the power of PowerShell with a simple demo. This time, I will create a .txt file with a list of database names. The PowerShell script will create databases using that list.
Creating databases with PowerShell from a list
First we need a list of database names. To do this, we will use a txt file. Attached to this article, we have a database.txt file that contains a list of database names. The content of the database.txt is the following:
marketing
products
research
Now we are going to save the database.txt content in a PowerShell variable. The PowerShell variables can store numbers, text and also txt files.
For example, the variable $list can store the word hello world.
$list="hello world"
To verify the content we use the echo.
echo $li
In this case we want to save the database.txt content in the $list variable. That’s why PowerShell is so powerful. It can do things with few lines of code.
$list=get-content c:\databases.txt
To verify that the list contains the database.txt content use the echo command.
echo $list
Finally, to create databases we are going to call the Invoke-sqlcmd. The invoke-sqlcmd let us run T-SQL queries in PowerShell:
$list | ForEach-Object {Invoke-SqlCmd -Query "create database $_"}
The foreach let us create a database for each member of the $list.
To verify that everything is OK, open the SQL Server Management Studio and verify that the new databases were created:
Conclusion
This simple demo shows how easy it is to work with powershell. You can interact with text files, the active directoy, Exchange and more. The future of the Administrative tasks is Powershell.