简体   繁体   中英

How can i retrieve username and password when retrieving Azure Database details via Powershell?

I can list Azure databases as follows:

  $servers = Get-AzSqlServer
   foreach($server in $servers)
   {
      $databases = Get-AzSqlDatabase -ServerName $server.ServerName -ResourceGroupName 
       $server.ResourceGroupName 
        foreach($db in $databases){
         Write-Host "Server " $db.ServerName  "Database " $db.DatabaseName 
            $server.SqlAdministratorLogin "SqlAdminPwd " 
            $server.SqlAdministratorPassword
            Invoke-SqlCmd -ServerInstance $db.ServerName -Database $db.DatabaseName - 
           Username <azuredb_admin_username> -Password 
                    <azuredb_admin_password> -Query 
              'select * from [dbo].[TableName]' 
       }
    }

$server.SqlAdministratorPassword is empty which is understandable. But in the next line I invoke a sqlcmd which requires the password.

How can i get and use the password?

PowerShell query should require login credential implicitly or explicitly through the command line. There are couple of ways to pass credentials.

  1. Store credentials in credentials manager and fetch the information from there example:

     $psCred = Get-StoredCredential -Target "ABCD" –AsCredentialObject
  2. Here is the code snippet to get the password using PowerShell

     $serverName = $db.ServerName $DB = $db.DatabaseName $credential = Get-Credential $userName = $credential.UserName.Replace("\","") $pass = $credential.GetNetworkCredential().password invoke-sqlcmd -query "select @@Servername" -database $DB -serverinstance $servername -username $username -password $pass -Query 'select * from [dbo].[TableName]'

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM