How to use PowerShell to create a SQL Virtual Machine in Azure

How to use PowerShell to create a SQL Virtual Machine in Azure

How to use PowerShell to create a SQL Virtual Machine in Azure

SQLShack

SQL Server training Español

How to use PowerShell to create a SQL Virtual Machine in Azure

June 4, 2015 by Daniel Calbimonte

Introduction

The first time that you create your VM in Azure manually using the UI is a very pleasant experience. However, when you have hundred and sometimes thousands of computers it is extremely exhausting and boring to create and configure it. With PowerShell, it is possible to automate several administrative tasks and create scripts to automatically create VMs, enable ports, download and create remote desktop files, administer services, etc. In this new chapter, we will show how to create a Virtual Machine in Azure with SQL Server installed using PowerShell.

Requirements

An Azure subscription. A local machine with Windows installed. The PowerShell installed (check my first article about PowerShell, step 1 to 5 for more information about the installation). Connect to Azure from PowerShell by creating and importing a PublishSettings file (see my article about PowerShell and Azure step 8 to 13 for more information).

Getting started

The first thing that you need to know is your subscription information. You can use the following command to get your subscription information: Get-AzureSubscription The command will provide all the Subscription information:
Figure 1. Subscription information The information that we need is the SubscriptionName. You could also use the following command to get just the required information: Get-AzureSubscription select SubscriptionName Once you have the SubscriptionName, store the information in a variable: $SubscriptionName= ‘Visual Studio Ultimate with MSDN’ In the Azure Portal you can find the same information just to compare by clicking in the user name> View my bill. This step is just to verify and compare PowerShell with the portal.
Figure 2. Billing information In the subscriptions, you will find the subscription name.
Figure 3. The type of subscription We also need the storageaccount. The storage is used to store information like backups, files and in this case the Virtual Machine information. We can get the list of StorageAccounts with the following command: Get-AzureStorageAccount select label The information displayed is the following:
Figure 4. The Azure Storage Accounts You can store the storageAccount information with this command: $storageaccount=’mysqlshackstorage’ You can compare this information with the Storage section in the Azure Portal.
Figure 5. The storage list in the Azure Portal You can also check the currentStorageAccount using the command of the step 1.
Figure 6. The current Storage Account Name Something important is the Location and Geo-Location. You can find this information using the following commands: Get-AzureStorageAccount select
label,location,geoprimarylocation The location is used to locate your service near you. That may improve the speed of your Services in Azure.
Figure 7. The storage, locaton and primary location. In this example the location will be West US. If you do not have an storage account you can create one with the following commands: $dclocation=’West US’ $storageaccount=’sqlshackstorage‘ New-AzureStorageAccount -StorageAccountName $storageaccount -Location $dclocation The $dclocation variable will store the location. You can check the storage created following the step 10. Another step is the image used to create the virtual machine. The following command will provide the images related to SQL Server: Get-AzureVMImage select ImageName The command will show all the Azure images including Servers with Linux, Oracle, SharePoint, SQL Server, etc. The images are used to easily create virtual machines with software installed instead of installing from zero.
Figure 8. The list of virtual Images. In this example, we will use a SQL Server 14 RTM Web Edition: $image=’fb83b3509582419d99629ce476bcb5c8__SQL-Server-2014-RTM-12.0.2361.0-Web-ENU-Win2012R2-cy14su05′ Now set the Azure Subscription Set-AzureSubscription -SubscriptionName $SubscriptionName -CurrentStorageAccount $storageaccount You will also need a CloudService name. First, let’s add a service name in a variable: $cloudServiceName = ‘sqlshackpsserv‘ You can create a new Azure service with the following commands: New-AzureService -ServiceName $cloudServiceName -Label "my service" -Location $dclocation You can verify the cloud service created in the portal.
Figure 9. The list of cloud services We will also need the Administrator username and password to login the Virtual Azure machine. $UserName = ‘Daniel‘
$Password = ‘Security12!@‘ You will also need a Virtual Machine name: $virtual_name = ‘VMSqlShack‘ Now, create a Virtual Machine with a User and Password using the cloudServiceName: New-AzureVMConfig -Name $virtual_name –InstanceSize Large –ImageName $image Add-AzureProvisioningConfig -Windows -Password $Password –AdminUsername $UserName New-AzureVM –ServiceName $cloudServiceName If everything is correct, you will be able to see the the Virtual Machine created in the Azure Portal:
Figure 10. The virtual machine created It may take some minutes for the virtual machine to start. You can get the virtual machine information using the following command: Get–AzureVM –ServiceName $cloudServiceName –Name $virtual_name The information displayed by the Get-AzureVM will be similar to this picture:
Figure 11. The VM information You can create a remote desktop file using the following command: Get-AzureRemoteDesktopFile –ServiceName $cloudServiceName -Name $virtual_name –LocalPath "c:\myvm\psVirtual.rdp" You can now connect to your machine by double clicking on the rdp file.
File 12. The rpd file Now you can connect to your machine with the credentials provided on step 20.
Figure 13. The virtual machine with SQL Server created Finally, if the machine is for testing purposes, you can stop the Virtual machine using this command (strongly recommended because Azure charges per minute of started machine): Stop-AzureVM –ServiceName $cloudServiceName –Name $virtual_name

Some typical errors

When you run this command: New-AzureVMConfig -Name $virtual_name –InstanceSize Large –ImageName $image Add-AzureProvisioningConfig -Windows -Password $Password –AdminUsername $UserName New-AzureVM –ServiceName $cloudServiceName A typical error is this one: Add-AzureProvisioningConfig : A parameter cannot be found that matches parameter name ‘MediaLocation’. When I had this error I just changed the virtual images (in step 14) to a different SQL Server image because the one used expired. When I run this command: New-AzureService -ServiceName $cloudSvcName -Label "MyLabel" -Location "DC-LOCATION" I received the following output: VERBOSE: 9:12:48 AM – Begin Operation: New-AzureService New-AzureService : ConflictError: The specified DNS name is already taken. At line:1 char:1 + New-AzureService -ServiceName $cloudSvcName -Label "MyLabel" -Location $dclocati … + CategoryInfo : CloseError: (:) [New-AzureService], CloudException + FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.ServiceManagement.HostedServices.NewAzureServiceCommand The solution is just to try to assign a diferent service name.

Conclusion

In this chapter, we learned how to create a virtual machine using PowerShell. First, you need to verify the subscription information, use an existing StorageAccount or create a StorageAccount and set Azure Subscriptions. You have to create an Azure Service. With that information, you can create a Virtual Machine assigning a user name and password. The last part is to create an rdp file to connect remotely to the virtual machine. Author Recent Posts Daniel CalbimonteDaniel Calbimonte is a Microsoft Most Valuable Professional, Microsoft Certified Trainer and Microsoft Certified IT Professional for SQL Server. He is an accomplished SSIS author, teacher at IT Academies and has over 13 years of experience working with different databases.

He has worked for the government, oil companies, web sites, magazines and universities around the world. Daniel also regularly speaks at SQL Servers conferences and blogs. He writes SQL Server training materials for certification exams.

He also helps with translating SQLShack articles to Spanish

View all posts by Daniel Calbimonte Latest posts by Daniel Calbimonte (see all) SQL Partition overview - September 26, 2022 ODBC Drivers in SSIS - September 23, 2022 Getting started with Azure SQL Managed Instance - September 14, 2022

Related posts

How to work handle SQL Azure Databases with PowerShell How to create an Azure SQL Database using the Cloud Shell How to import a sample bacpac file to an Azure SQL Database using sqlpackage and PowerShell How to migrate your database to an Azure Virtual Machine Using PowerShell to monitor your Azure Machine 2,939 Views

Follow us

Popular

SQL Convert Date functions and formats SQL Variables: Basics and usage SQL PARTITION BY Clause overview Different ways to SQL delete duplicate rows from a SQL Table How to UPDATE from a SELECT statement in SQL Server SQL Server functions for converting a String to a Date SELECT INTO TEMP TABLE statement in SQL Server SQL WHILE loop with simple examples How to backup and restore MySQL databases using the mysqldump command CASE statement in SQL Overview of SQL RANK functions Understanding the SQL MERGE statement INSERT INTO SELECT statement overview and examples SQL multiple joins for beginners with examples Understanding the SQL Decimal data type DELETE CASCADE and UPDATE CASCADE in SQL Server foreign key SQL Not Equal Operator introduction and examples SQL CROSS JOIN with examples The Table Variable in SQL Server SQL Server table hints – WITH (NOLOCK) best practices

Trending

SQL Server Transaction Log Backup, Truncate and Shrink Operations Six different methods to copy tables between databases in SQL Server How to implement error handling in SQL Server Working with the SQL Server command line (sqlcmd) Methods to avoid the SQL divide by zero error Query optimization techniques in SQL Server: tips and tricks How to create and configure a linked server in SQL Server Management Studio SQL replace: How to replace ASCII special characters in SQL Server How to identify slow running queries in SQL Server SQL varchar data type deep dive How to implement array-like functionality in SQL Server All about locking in SQL Server SQL Server stored procedures for beginners Database table partitioning in SQL Server How to drop temp tables in SQL Server How to determine free space and file size for SQL Server databases Using PowerShell to split a string into an array KILL SPID command in SQL Server How to install SQL Server Express edition SQL Union overview, usage and examples

Solutions

Read a SQL Server transaction logSQL Server database auditing techniquesHow to recover SQL Server data from accidental UPDATE and DELETE operationsHow to quickly search for SQL database data and objectsSynchronize SQL Server databases in different remote sourcesRecover SQL data from a dropped table without backupsHow to restore specific table(s) from a SQL Server database backupRecover deleted SQL data from transaction logsHow to recover SQL Server data from accidental updates without backupsAutomatically compare and synchronize SQL Server dataOpen LDF file and view LDF file contentQuickly convert SQL code to language-specific client codeHow to recover a single table from a SQL Server database backupRecover data lost due to a TRUNCATE operation without backupsHow to recover SQL Server data from accidental DELETE, TRUNCATE and DROP operationsReverting your SQL Server database back to a specific point in timeHow to create SSIS package documentationMigrate a SQL Server database to a newer version of SQL ServerHow to restore a SQL Server database backup to an older version of SQL Server

Categories and tips

►Auditing and compliance (50) Auditing (40) Data classification (1) Data masking (9) Azure (295) Azure Data Studio (46) Backup and restore (108) ►Business Intelligence (482) Analysis Services (SSAS) (47) Biml (10) Data Mining (14) Data Quality Services (4) Data Tools (SSDT) (13) Data Warehouse (16) Excel (20) General (39) Integration Services (SSIS) (125) Master Data Services (6) OLAP cube (15) PowerBI (95) Reporting Services (SSRS) (67) Data science (21) ►Database design (233) Clustering (16) Common Table Expressions (CTE) (11) Concurrency (1) Constraints (8) Data types (11) FILESTREAM (22) General database design (104) Partitioning (13) Relationships and dependencies (12) Temporal tables (12) Views (16) ►Database development (418) Comparison (4) Continuous delivery (CD) (5) Continuous integration (CI) (11) Development (146) Functions (106) Hyper-V (1) Search (10) Source Control (15) SQL unit testing (23) Stored procedures (34) String Concatenation (2) Synonyms (1) Team Explorer (2) Testing (35) Visual Studio (14) DBAtools (35) DevOps (23) DevSecOps (2) Documentation (22) ETL (76) ►Features (213) Adaptive query processing (11) Bulk insert (16) Database mail (10) DBCC (7) Experimentation Assistant (DEA) (3) High Availability (36) Query store (10) Replication (40) Transaction log (59) Transparent Data Encryption (TDE) (21) Importing, exporting (51) Installation, setup and configuration (121) Jobs (42) ▼Languages and coding (686) Cursors (9) DDL (9) DML (6) JSON (17) PowerShell (77) Python (37) R (16) SQL commands (196) SQLCMD (7) String functions (21) T-SQL (275) XML (15) Lists (12) Machine learning (37) Maintenance (99) Migration (50) Miscellaneous (1) ►Performance tuning (869) Alerting (8) Always On Availability Groups (82) Buffer Pool Extension (BPE) (9) Columnstore index (9) Deadlocks (16) Execution plans (125) In-Memory OLTP (22) Indexes (79) Latches (5) Locking (10) Monitoring (100) Performance (196) Performance counters (28) Performance Testing (9) Query analysis (121) Reports (20) SSAS monitoring (3) SSIS monitoring (10) SSRS monitoring (4) Wait types (11) ►Professional development (68) Professional development (27) Project management (9) SQL interview questions (32) Recovery (33) Security (84) Server management (24) SQL Azure (271) SQL Server Management Studio (SSMS) (90) SQL Server on Linux (21) ►SQL Server versions (177) SQL Server 2012 (6) SQL Server 2016 (63) SQL Server 2017 (49) SQL Server 2019 (57) SQL Server 2022 (2) ►Technologies (334) AWS (45) AWS RDS (56) Azure Cosmos DB (28) Containers (12) Docker (9) Graph database (13) Kerberos (2) Kubernetes (1) Linux (44) LocalDB (2) MySQL (49) Oracle (10) PolyBase (10) PostgreSQL (36) SharePoint (4) Ubuntu (13) Uncategorized (4) Utilities (21) Helpers and best practices BI performance counters SQL code smells rules SQL Server wait types © 2022 Quest Software Inc. ALL RIGHTS RESERVED. GDPR Terms of Use Privacy
Share:
0 comments

Comments (0)

Leave a Comment

Minimum 10 characters required

* All fields are required. Comments are moderated before appearing.

No comments yet. Be the first to comment!