Azure/Powershell: Checking to see if a SQL Server exists - sql-server

I'm coming from a C# background, and this is my first foray into Powershell. I'm trying to write a Powershell script that does a whole bunch of stuff in Azure, among them:
Check to see if a SQL Server instance exists
Create a server (using New-AzureRmSqlServer) if it does not
Create a new DB on the server
... and some other stuff
My first problem is that if the server already exists, I don't need to create it; I can just go directly to the DB creation. However, I can't seem to make that work.
I tried Get-AzureRmSqlServer, but that errors out if it can't find the server I'm looking for. Finally, I went with this function to return $true if found and $false if not:
function Check-For-Server
{
Param(
[Parameter(Mandatory=$true)]
[String]
$ServerName
)
if (Test-AzureName -Name $ServerName)
{
return $false
}
else
{
return $true
}
}
Here's the problem: I'm getting the following error:
Test-AzureName : Parameter set cannot be resolved using the specified named parameters.
At C:\src\Powershell\test.ps1:10 char:9
+ if (Test-AzureName -Name $ServerName)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Test-AzureName], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.WindowsAzure.Commands.CloudService.TestAzureNameCommand
Does anyone know how to get around this? Google was absolutely no help, at least as far as Test-AzureName with this particular error message. I thought of trying one of the -Service/ServiceBusName/Storage/Website arguments, but I'm not sure which is even applicable here. Or if it's even relevant -- the error message doesn't appear to indicate that I'm actually missing a parameter, just that the one I provided is somehow bad.
Oh, and if it helps, here's the call to Check-For-Server:
$sqlServerName = "test_db_server"
Check-For-Server -ServerName $sqlServerName
Thanks!

$serverInstance = Get-AzureRmSqlServer -ServerName $serverName -ResourceGroupName $resourceGroupname -ErrorAction SilentlyContinue
if ($serverInstance) { do stuff }
else { do other stuff }

Related

How do change a users permission to connect to database engine through powershell in ssms?

I'm currently writing a script to add users automatically. So far I can add a new SQL Login with the sqlserver modules Add-SqlLogin cmddlet. And I can add the database mapping for the user with another script I've found.
What remains is to actually allow the user to connect to the database (see image). I haven't found a way to do that through powershell yet. Can anyone point me to a solution?
The option I wish to set through powershell
After another hour of googling I have found a solution:
$ServerInstance = "server"
$name = "user"
$action = "Grant"
$permission = "ConnectSql"
$server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $ServerInstance
$perm = New-Object Microsoft.SqlServer.Management.Smo.ServerPermissionSet
$perm.$($permission.ToString()) = $true
switch ($action)
{
'Grant' { $server.Grant($perm,$name) }
'Deny' { $server.Deny($perm,$name) }
'Revoke' { $server.Revoke($perm,$name) }
}
How to use Powershell to modify SQL login permission? as answered by Chad Miller.

SMO : Get Server Permission Set for a login (ServerPermissionSet)

Trying to get a ServerPermissionSet for a login and apply it to a new login. Can't seem to grasp if there is a relationship between the ServerPermissionSet and a Server.Login, or if there is a better way to do this. I can do this with tSQL, but am trying to look at this from the SMO perspective. Here is some sudo code on what I am trying to accomplish.
$server = new-object ('Microsoft.SqlServer.Management.Smo.Server')
"my_server"
$sps = new-object -TypeName
Microsoft.SqlServer.Management.SMO.ServerPermissionSet
$newlogin = new-object ('Microsoft.SqlServer.Management.Smo.Login') $Server,
"new_login"
$oldlogin = $server.Logins["old_login"]
// THIS PART OBVIOUSLY DOESN'T WORK
$newlogin.Create("password")
$sps = $oldlogin.ServerPermissionSet
$server.Grant($sps,"new_login")
I'm using the code example here to inform my answer:
$server = new-object ('Microsoft.SqlServer.Management.Smo.Server')
"my_server"
$newlogin = new-object ('Microsoft.SqlServer.Management.Smo.Login') $Server,
"new_login"
$newlogin.Create("password")
$sps = $server.EnumServerPermissions("old_login")
$server.Grant($sps,"new_login")
That is, you have to ask the server to enumerate the server permissions for old_login which will generate a ServerPermissionSet[] which you can then pass to the Grant method on the server object.
But I do have to ask: is there a reason not to use a server-level role to encapsulate these permissions and just grant membership in the role to the new login?

Why is the Logins property null?

I'm trying to add a Windows user to an SQL Server. This works fine. However, if the user is already there, I don't want to get an error. If it's already there, that's fine. So I thought I would just check before creating it:
$AccountName = $args[0]
$ComputerName = $args[1]
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | Out-Null
$sqlSrv = New-Object 'Microsoft.SqlServer.Management.Smo.Server' ($ComputerName)
$sqlSrv.Refresh() # TRIED DIFFERENT THINGS HERE, REFRESH, INITIALIZE...
$login = $sqlSvr.Logins[$AccountName] # HERE .Logins IS NULL
if ($login -eq $null) {
$login = New-Object 'Microsoft.SqlServer.Management.Smo.Login' ($sqlSrv, $AccountName)
$login.Name = $AccountName
$login.LoginType = 'WindowsUser'
$login.PasswordPolicyEnforced = $false
$login.Create()
}
I don't know why the Logins Property of the SQL Server class is null. I can see the existing logins in SQL Management Studio.
Can anybody tell me how to properly check if a login exists before creating it? With Roles and Databases, the Server's properties seem to be filled.
I'm using Sql Server Express Version 11.0.5058.0 (I think that's 2012) and Powershell Version is 5.0.10586.117.
Change this to this $sqlSvr.Logins to $sqlSrv.Logins
$sqlSvr.Logins to $sqlSrv.Logins

phpmyadmin: Connection failed: Unknown database.

I'm a beginner and a teacher trying to make a quiz and connect to the database. I'm using MAMP 7.0.6, also installed XAMPP on my window. I had a database called "students" on phpmyadmin and a script like this:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "students";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
It works fine when I tried to connect to the database without the $dbname, however, when I included that it says "Connection failed: Unknown database 'students'". I'm sure the name and username, password and stuff is correct, even though I don't know why the password has to be "" instead of the one shown on my phpmyadmin, but it works so I'll just leave it for later unless some of you would like to spend the time to explain it to me.
I just want to make this work asap coz it has been bugging me for a few days and I still can't find the solution online. I need to get the quiz done by mid August so thank you so much in advance!!!!

Powershell 2.0 Ping list of computers and send email on failure

I am new at PowerShell and I have been researching this issue, but I have not been able to find what I am looking for yet. The site is still using PowerShell 2, and it cannot be upgraded.
I have a list of servers that I want to ping to verify that they are up, and I am using a text file to populate the names. I have the pinging part of the script working and the emailing part working just fine. Now I am trying to combine the two to email about a specific server that fails.
I am using the following:
Test-Connection -ComputerName (Get-Content Computers.txt) -Delay 5 -Quiet
This returns the boolean values of true or false for each computer.
I know that the Get-Content automatically creates an array. So is the best way to get the results written as an associative array, or is there a way to get the Test-Connection to loop one at a time through the Computers.txt array and then just send the email on a failure when it is on that specific server?
Try this:
Get-Content Computers.txt | ForEach-Object {
if (Test-Connection -ComputerName $_ -Delay 5 -Quiet) {
#Send email that it was a success
} else {
#Computer unreachable
}
}
Basically you pipe the list of computers to a foreach-object loop, and iterate through the list, pinging each computer and sending the email.

Resources