Creating Azure SQL Database Server connection context New-AzureSqlDatabaseServerContext - powershell

I am trying to create an Azure SQL Database connection context e.g.
$cred = Get-Credential
$ctx = New-AzureSqlDatabaseServerContext -ServerName “mydatabasename” -credential $cred
or
$pwd = ConvertTo-SecureString "[password1234]" -AsPlainText -Force;
$cred1 = New-Object System.Management.Automation.PSCredential -ArgumentList "databaseadmin", $pwd
New-AzureSqlDatabaseServerContext -ServerName "myservername" -Credential $cred1
And the response is:
New-AzureSqlDatabaseServerContext : Object reference not set to an instance of an object.
At line:2 char:8
+ $ctx = New-AzureSqlDatabaseServerContext -ServerName “myservername” - ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzureSqlDatabaseServerContext], NullReferenceException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.SqlDatabase.Database.Cmdlet.NewAzureSqlDatabaseServerContext
I've been through the docs and google searches but to no avail.
https://msdn.microsoft.com/en-us/library/dn546736.aspx
http://sqlmag.com/powershell/manage-azure-sql-databases-powershell
Thanks
Pavel

I recently ran into this issue in a PS runbook. After doing some searching, I found a solution that worked for me. Hopefully it will help you.
The error message isn't particularly helpful (big surprise), but the null object being referenced is the Azure subscription; I'm assuming the exception bubbles up from within the cmdlet rather than being thrown by your own code. By adding these three lines to my code:
$cert = Get-AutomationCertificate -Name $automationCertificateName;
Set-AzureSubscription -SubscriptionName $subName -Certificate $cert -SubscriptionId $subID;
Select-AzureSubscription -Current $subName;
I was able to get past the exception. Above, $automationCertificateName is a variable asset that I added to the automation account. See https://github.com/Microsoft/sql-server-samples/tree/master/samples/manage/azure-automation-automated-export for details about how to set that up.

Here is how I successfully created connection context:
$sqlServerUser = "test-user"
$sqlServerUserPassword = "P#$$w0rd"
$sqlServerName = "mysqlserver"
$sqlCred = New-Object System.Management.Automation.PSCredential($sqlServerUser, ($sqlServerUserPassword | ConvertTo-SecureString -asPlainText -Force))
$sqlContext = New-AzureSqlDatabaseServerContext -ServerName $sqlServerName -Credential $sqlCred
Please see this for more details.

Related

Issues with running script without credentials dialog box

I'm trying to run through a powershell script that creates a computername and places that computer in the right OU in AD. The only issue is I need to enter credentials for this to happen, but I want to do it without having to enter the credentials into the powershell credential dialog box.
I used the System.Management.Automation.PSCredential, but that is was apparently was giving me the dialog box.
$secpasswd = ConvertTo-SecureString 'xxxxxx' -AsPlainText -Force
$mycreds = New-Object System.Managemnet.Automation.PSCredential("xxxx", $secpasswd)
Trying to the use the code above without a dialog box popping up
New-Object : Cannot find type [System.Managemnet.Automation.PSCredential]: verify that the assembly containing this type is loaded.
At line:2 char:12
+ $mycreds = New-Object System.Managemnet.Automation.PSCredential("xxxx ...
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidType: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand
You made a typo on "Managemnet". It should be -
$mycreds = New-Object System.Management.Automation.PSCredential("xxxx", $secpasswd)
It appears you made a typo in your code: Managemnet should be Management, as in System.Management.Automation. That is why your error is being thrown.
However, there is no need to use the full definition for PSCredential. Use the following instead:
$secpasswd = ConvertTo-SecureString 'xxxxxx' -AsPlainText -Force
$mycreds = New-Object PSCredential("xxxx", $secpasswd)
This does not show a dialog box.

Invoke-Command with -credentials

I want to invoke a command on a remote server, I do not want to have to put in the password to run the script. I've tried encrypting the password and storing it in a txt file.
$username = "Mydomain\service.account"
$password = cat C:\username-password-encrypted.txt | convertto-securestring
$cred = new-object -typename System.Management.Automation.PSCredential - argumentlist $username, $password
Invoke-command $cred -Computer myserver -scriptblock {param([string]$LocalUser); Add-PSSnapin Citrix* ; Get-BrokerSession -max 10000 | Where-Object brokeringusername -eq "mydomain\$($LocalUser)" | Stop-BrokerSession} -ArgumentList $user
Here is the error I get
Invoke-Command : A positional parameter cannot be found that accepts argument 'System.Management.Automation.PSCredential'.
At \\uncpath\citrix\Installation Media\Citrix\Ticketing_script\Ticketing_Script - Copy (3).ps1:70 char:1
+ Invoke-command $cred -Computer MyServer -scriptblock {param([s ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-Command], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.InvokeCommandCommand
There has to be an easier way to run this command on myserver without having to put in the password every time.
You just have to specify the -Credential parameter:
Invoke-command -Credential $cred -Computer myserver -scriptblock {param([string]$LocalUser); Add-PSSnapin Citrix* ; Get-BrokerSession -max 10000 | Where-Object brokeringusername -eq "mydomain\$($LocalUser)" | Stop-BrokerSession} -ArgumentList $user
4 years later but here goes:
Frode F. had the right idea in the comments. Your third line has - argumentlist but it must be -ArgumentList, otherwise it will throw New-Object : A positional parameter cannot be found that accepts argument 'ArgumentList'.
Also, when I copy and run your exact code it does not throw the same error which leads me to believe that the code you're running is not the same as the one you've written here. Here are the different errors you've received and the reasons for them:
Incorrect syntax
A positional parameter cannot be found that accepts argument 'System.Management.Automation.PSCredential'.
This means that you've not specified the flag correctly, Powershell thinks you're using a flag or parameter called System.Management.Automation.PSCredential. You can simulate this by adding a hyphen like New-Object -TypeName - System.Management.Automation.PSCredential and see for yourself, so your syntax is wrong somewhere.
Incorrect password format
Cannot find an overload for "PSCredential" and the argument count: "2".
This means that the $Password is not in the correct format. You're importing a file called password-encrypted.txt but after this you pass it to ConvertTo-SecureString. Are you sure that the information in the password-encrypted.txt file is passed to both ConvertTo-SecureString and then to ConvertFrom-SecureString before you saved it, like so?
"MyPassword" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "C:\username-password-encrypted.txt"
For more information on how to deal with passwords in Powershell, see this post that goes into detail on how to do credentials in Powershell:
https://www.pdq.com/blog/secure-password-with-powershell-encrypting-credentials-part-1/
In conclusion
If you run the code you've provided here using both -ArgumentList (instead of - argumentlist) and -Credentials $creds like others have suggested it should run fine. You're most likely not running the code that you've provided here because with these two adjustments the code runs.

Start-AzureSqlDatabaseExport: Object reference not set to an instance of an object

I am trying to start an export of a SQL Azure database to a blob. However, after trying different approaches and searching the web I can't find a way to make it work.
$exportRequest = Start-AzureSqlDatabaseExport -SqlConnectionContext $SqlContext -StorageContainer $Container -DatabaseName 'Users' -BlobName 'autobackupotest.bacpac' -Verbose -Debug
The line above results in:
DEBUG: 2:05:14 PM - StartAzureSqlDatabaseExport begin processing with ParameterSet 'ByContainerObject'.
WARNING: Client Session Id: '111746f6-65c2-4ba1-b7c6-52a9171ee6-2016-03-28 08:15:58Z'
WARNING: Client Request Id: 'f20b3326-a6c4-48d7-beb0-6ce7b17585-2016-03-28 11:05:14Z'
Start-AzureSqlDatabaseExport : Object reference not set to an instance of an object.
At C:\tests\thirdversion.ps1:29 char:22
+ $exportRequest = Start-AzureSqlDatabaseExport -SqlConnectionContext $SqlCont ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Start-AzureSqlDatabaseExport], NullReferenceException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.SqlDatabase.Database.Cmdlet.StartAzureSqlDatabaseExport
DEBUG: 2:05:19 PM - StartAzureSqlDatabaseExport end processing.
I verified the variables I use for this cmdlet and they are not null. Prior to that cmdlet I use the following code:
Import-Module Azure
Import-Module Azure.Storage
Get-AzureRmSubscription –SubscriptionName “Production” | Select-AzureRmSubscription
# Username for Azure SQL Database server
$ServerLogin = "username"
# Password for Azure SQL Database server
$serverPassword = ConvertTo-SecureString "abcd" -AsPlainText -Force
# Establish credentials for Azure SQL Database Server
$ServerCredential = new-object System.Management.Automation.PSCredential($ServerLogin, $serverPassword)
# Create connection context for Azure SQL Database server
$SqlContext = New-AzureSqlDatabaseServerContext -FullyQualifiedServerName “myspecialsqlserver.database.windows.net” -Credential $ServerCredential
$StorageContext = New-AzureStorageContext -StorageAccountName 'prodwad' -StorageAccountKey 'xxxxx'
$Container = Get-AzureStorageContainer -Name 'automateddbbackups' -Context $StorageContext
$exportRequest = Start-AzureSqlDatabaseExport -SqlConnectionContext $SqlContext -StorageContainer $Container -DatabaseName 'Users' -BlobName 'autobackupotest.bacpac' -Verbose -Debug
What could be wrong here? That exception message does not provide any detail.
I tested your code and it works fine on my side.
Run Login-AzureRmAccount to login before Get-AzureRmSubscription –SubscriptionName “Production” | Select-AzureRmSubscription, verify that the subscription Production exists in current tenant. And double check the username,password for SQL server, StorageAccount,StorageAccountKey,ContainerName are all correct.

New-PSsession not working in Script

I have a strange problem with one of my servers :
I am trying to open a PSsession with it.
If I copy my script directly in powershell everything works fine, but if i run it via a .ps1 file I get a access denied error.
The same sript works on multiple machines except this one.
Additonal information:
Executing Server : Server 2012
Target Server2003SP2
Another Server2003SP2 is working fine without a Problem
the Client Server was configured using :
Enable-PSRemoting -Force
Set-Item wsman:\localhost\client\trustedhosts MY2012Server -concatenate -force
Restart-Service WinRM
And the Error Message:
New-PSSession : [Server2003SP2] Connecting to remote server Server2003SP2 failed with the following error message : Access is denied. For more information,
Help topic.
At C:\Users\Administrator\Desktop\Script.ps1:23 char:13
+ $Session = New-PSSession -ComputerName $Servername -credential $Cred #-sessionO ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed
Edit : My full SCript as requested :
$Password = "Hereismypasswordwith#and€init"
$Username = "Servername\Administrator"
$Servername = "Servername"
$Language = {
$oscode = Get-WmiObject Win32_OperatingSystem -ErrorAction continue
$oscode = $oscode.oslanguage
$switch = switch ($oscode){
1031 {"Deutsch"};
1033 {"English"};
default {"English"};
}
write-host $switch
return $switch
}
$SecurePassWord = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $Username, $SecurePassWord
$pssessionoption = new-pssessionoption -operationtimeout 7200000 -IdleTimeout 7200000
$Session = New-PSSession -ComputerName $Servername -credential $Cred -sessionOption $pssessionoption
Invoke-Command -Session $Session -Scriptblock $Language
Remove-PSSession -Session $Session
UPDATE :
it seems to be something within the Char encoding.
the password in the ps1 file produces a difrent output for the € in it :
in the ps1. ¬
in the ps window : ?
if i pass the Password as a Paramter it also works.
$password.gethash() also prouces difrent outputs. codepage is the same though (chcp)
the script was created in notepad++
Changing / Converting to ansi from UTC without BOM fixed the issue.. jesus crist who thinks about stuff like that / why the hell was it set to this value..

Powershell - Secure String for Passwords and SFTP

I am trying to implement a way to use a stored secure string so that my SFTP password is not visiable in the script. For example, I'd like to generate a variable $password that could be used instead. I found the following examples online but I can't get them to work unfortunately. I've done something similar in the past but can find my notes or links to the website that explained how to complete the task.
read-host -assecurestring | convertfrom-securestring | out-file C:\securestring.txt
$pass = cat C:\securestring.txt | convertto-securestring
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist "test",$pass
Here is my script. Here is a link to the snapin if anyone is interested. http://www.k-tools.nl/index.php/sftp-in-powershell/
#Add the SFTP snap-in
Add-PSSnapin KTools.PowerShell.SFTP
#Define some variables
$sftpHost = "ftp.domain.com"
$userName = "user"
$userPassword = "password"
$localFile = "C:\bin\emp1.xlsx"
#Open the SFTP connection
$sftp = Open-SFTPServer -serverAddress $sftpHost -userName $userName -userPassword $userPassword
#Upload the local file to the root folder on the SFTP server
$sftp.Put($localFile)
#Close the SFTP connection
$sftp.Close()
Again, thanks for everyones help!
UPDATE
I tried this:
$pass = cat c:\bin\ftpcreds.txt | convertto-securestring
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist "usertest1",$pass
$sftpHost = "ftp.domain.com"
$userName = $mycred.username
$userPassword = $mycred.password
$sftp = Open-SFTPServer -serverAddress $sftpHost -userName $userName -userPassword $userPassword
$sftp.Put($localFile)
$sftp.Close()
And get this error:
Method invocation failed because [Tamir.SharpSsh.jsch.JSchException] doesn't contain a method named 'Put'.
At C:\bin\SFTP Upload Samples.ps1:21 char:1
+ $sftp.Put($localFile)
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Method invocation failed because [Tamir.SharpSsh.jsch.JSchException] doesn't contain a method named 'Close'.
At C:\bin\SFTP Upload Samples.ps1:36 char:1
+ $sftp.Close()
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Any suggestions?
Thanks!
If your SFTP is wanting to use a decrypted version of your secured password then you'll want to extract it from your $mycred by:
$userpassword = $mycred.getnetworkcredential().password.tostring()