Windows password does not work for Powershell Credential Request - sql-server

I am aware I can set up Powershell credentials Get-Credential for my own scripts. But when I use the following command Get a SQL Server instance on a computer in a PS terminal:
Get-SqlInstance -Credential laptop-ql9k5dk6\david -ServerInstance "laptop-ql9k5dk6\sqlexpress2"
I expect that I am going to be asked for my Windows password.
Here is my thinking:
Logging in to my SQL Server instance (laptop-ql9k5dk6\david) via MS SQL Server Management Studio (using Windows Authentication) uses my already logged on status. Otherwise I would need my Windows password.
Since my script is asking for a password for laptop-ql9k5dk6\david; I think it must be my Windows password?
So. Why does my Windows Password fail when my PowerShell one-liner (shown above) asks me for a password?
PowerShell credential request
Enter your credentials.
Password for user laptop-ql9k5dk6\david: **************
Get-SqlInstance: Failed to connect to server laptop-ql9k5dk6\sqlexpress2.
On MSSM I can also login via SQL Login but for that the username is different from the Windows Authentication user above.
Note: My current Windows password is good. I use it regularly without making mistakes/leaving CAPs on etc.

$role = "sql"
$user = read-host "user for $role"
$pwd = read-host "password:" -AsSecureString
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $user, $pwd
Get-SqlInstance -Credential $cred -ServerInstance "laptop-ql9k5dk6\sqlexpress2"
perhaps the cmdlet does not support Integrated Security=true;

Incorrect Password: One possibility is that you may be entering the wrong password. Double-check to ensure that you are entering the correct password for your Windows account.
Locked Account: If you have entered the wrong password too many times, your account may become locked. This can prevent you from accessing your account until it is unlocked. You can try unlocking your account by following the steps provided by your system administrator.
Expired Password: It is also possible that your Windows password has expired. In this case, you will need to reset your password before you can log in. You can reset your password by following the steps provided by your system administrator.
Credential Manager: If you are running your PowerShell script from a different machine or domain, your Windows credentials may not be recognized. In this case, you can try storing your credentials in the Windows Credential Manager. You can do this by running the cmdkey command in the command prompt or PowerShell.
System Permissions: If you are trying to run a PowerShell script that requires elevated privileges, you may need to run PowerShell as an administrator. Right-click on the PowerShell icon and select "Run as administrator".

Related

New-SPConfigurationDatabase cannot connect to database/master unless I am logged into Windows desktop session

This one is a doozy. Note, I'm using Ansible to automate, and that's part of the issue.
My ansible playbook fails with the following if I execute it remotely without being logged into the server:
"stderr": "New-SPConfigurationDatabase : Cannot connect to database master at SQL server at SERVERNAME.fqdn.
The database might not exist, or the current user does not have permission to connect to it.
I have a step in my playbook that confirm I am an AD user with the correct permissions on the database.
Furthermore, this playbook works if I happen to be logged into the server (target, where this is running) while the playbook runs. Note, there should be nothing linking the logged-in session to the ansible session, but it's like Active Directory (Kerberos?) only trusts this user when it's "really" logged in.
I did another quick test to see what SQL thought the user was trying to connect, as another task in the playbook:
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = tcp:SERVERNAME; Database = master; Authentication=Active Directory Integrated;Encrypt = False;TrustServerCertificate=True;"
$SqlConnection.open()
and when I'm logged into the desktop it connects without error. When I'm not logged into the desktop simultaneously, it reports fails with Login failed for user 'NT AUTHORITY\\ANONYMOUS "
Oh, and the ansible task is running with elevated privs; I don't understand why the SQL client seems to change it's mind which credentials to use based on whether the account is logged into with RDP.

Unable to Process Partition in Power BI Premium Model Using SQL Server Agent Powershell CmdExec Step

I am trying to use Analysis Services Cmdlets to process partitions on a Power BI Premium Model. My PowerShell script works fine when run from ISE, the command line, and when scheduled using windows task scheduler; however, when I try to schedule the PowerShell script using a SQL Server 2019 Agent job using a step type of
Operating System (CmdExec)" the following error message is encountered.
Message Executed as user: MyDomain\MyUser. Invoke-ProcessPartition : The
connection string is not valid. At
C:\Users\MyUser\Desktop\PS1\SSAS\wtf.ps1:15 char:11 + $asResult =
Invoke-ProcessPartition -Credential $UserCredential -Server...+
CategoryInfo : NotSpecified: (:) [Invoke-ProcessPartition],
ConnectionException + FullyQualifiedErrorId :
Microsoft.AnalysisServices.ConnectionException,Microsoft.AnalysisServices.PowerShell.Cmd
lets.ProcessPartition.
I have followed the steps in this blog article to setup the job. The same windows user is used in all three run scenarios. The SQL server is my local development SQL server of which the windows user is SA on the SQL Server and Windows Admin. The same machine the SQL Instance is on is being used for successfully executing the other three ways of running the PS scripts, (ISE, Command Line, & Windows Task Scheduler)
If I run the following from the command line on the same machine as the SQL server, my local host, the PowerShell script runs successfully.
PowerShell -File "C\Users\MyUser\Desktop\PS1\SSAS\wtf.ps1"
Below is my PowerShell script modified to be as small as possible to demonstrate issue and of course sensitive information redacted. Thanks in advance for any help, I'm at a loss at how to proceed. I really need this to work from the SQL agent so I don't have to guess when steps that the processing depends on have completed.
$ErrorActionPreference=”Stop”
Import-Module "SqlServer"
$User = "MyUser#MyDomain.com"
$PWord = ConvertTo-SecureString -String "MyPassword" -AsPlainText -Force
$UserCredential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $User, $PWord
$server = "powerbi://api.powerbi.com/v1.0/myorg/MyWorkspace"
$db = "MyModel"
$asResult = Invoke-ProcessPartition -Credential $UserCredential -Server $server -PartitionName "DimDate" -TableName "DimDate" -Database $db -RefreshType "Full"
The step code in my job is:
powershell -File "C:\Users\MyUser\Desktop\PS1\SSAS\wtf.ps1"
UPDATE:
I have discovered that if I target an on-prem SSAS server, the exact same code, with the exception of the server variable, does work using the SQL Agent method, but of course switching to on-prem is not what I desire.
UPDATE 2:
When I right click on a job within SSMS, and click "Start PowerShell" this opens up a SQL Server PowerShell Window. If I try executing the script this way I get the below error message. The account being used does not have MFA enabled.
Unable to obtain authentication token using the credentials provided.
If your Active Directory tenant administrator has configured
Multi-Factor Authentication or if your account is a Microsoft Account,
please remove the user name and password from the connection string,
and then retry. You should then be prompted to enter your credentials.
If I don't pass a credential to the Invoke-ProcessPartition command using the SQL Server PowerShell window, I get prompted for credentials and the call works. Of course I can't use this as a workaround because I need it to run unattended.
I also tried opening PowerShell ISE as the account being used for authentication to the Workspace in the PS script and it also gives the same error as the SQL Server Agent Job does.
The connection string is not valid.
I have found a solution to the issue. The resolution was twofold.
First problem was that when PowerShell was being run from the SQL Server Agent, the Version of the SqlServer module was an older outdated version. I found this out by executing a ps1 file from the SQL Server Agent Job using the following code and looking in the job history results.
Get-Command -module sqlserver invoke*
I tried running
Install-Module sqlserver -AllowClobber -Scope AllUsers
as an admin but it did not update the SqlServer module the SQL agent was running. Instead I created a ps1 file that simply runs
Install-Module sqlserver -AllowClobber -Scope CurrentUser -Force
and called the script using a SQL Agent CMD task and this updated the SqlServer module version. After this I started getting a more useful error message:
Unable to obtain authentication token using the credentials provided.
If your Active Directory tenant administrator has configured
Multi-Factor Authentication or if your account is a Microsoft Account,
please remove the user name and password from the connection string,
and then retry. You should then be prompted to enter your
credentials
With this new error message, I decided to try an alternate way of supplying credentials by utilizing Azure Service Principals. This new method resulted in success from all PowerShell methods including SQL Server Agent Job. The steps implemented are outlined in this Power BI Documentation.
The final PS code looks like this.
$ErrorActionPreference=”Stop”
Import-Module "SqlServer"
$AppId = "AAD_App_Registration_Application_Client_Id"
$TenantId = "AAD_App_Registration_Directory_Tenant_Id"
$AppSecret = "AAD_App_Registration_CertificatesAndSecrets_ClientSecret"
$PWord = ConvertTo-SecureString -String $AppSecret -AsPlainText -Force
$Credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $AppId, $PWord
Invoke-ProcessPartition -Server "powerbi://api.powerbi.com/v1.0/myorg/MyModel" -PartitionName "DimDate" -TableName "DimDate" -Database "MyModel" -RefreshType "Full" -ServicePrincipal -ApplicationId $AppId -TenantId $TenantId -Credential $Credential

How to Restart SQL Reporting Service with Account and Password?

In Windows 2003 Server, I have a service running called 'SQL Server Reporting Services'.
This service will Stop at times, and when I try to Start it, it would give an Error as:
'Error 1069: The Service did not start due to a logon failure.'
After which, I would go to Properties -> Logon -> this account -> Give Username and Password.
After Applying the Changes, I can start the Service.
How do I go about writing a Script which would Automate this setting username and password and starting the Service? Also, is there any way to check if the Service is in a Run State and if not, script the logon step and start it?
Thank you.
I would suggest installing powershell for server 2003.
Have a look at this Powershell script to change service account.
You can user get-service to find if the service is running.
Something like the following could help. (For a Windows machine)
----> Refresh_SSRS.ps1
Stop-Service “SQL Server Reporting Services (SQLSRV)”
Start-Service “SQL Server Reporting Services (SQLSRV)”
$wc = New-Object system.net.webClient$wc
$cred = [System.Net.CredentialCache]::DefaultNetworkCredentials
$wc.Credentials = $cred
$src = $wc.DownloadString(“http://ComputerNamexxx/Reports_xxxxxx/Pages/Folder.aspx“)
---->Run in Task Scheduler - on a regular occurance - where the user account can be assoicated:
Powershell.exe
-ExecutionPolicy Bypass -File C:\commands\Refresh_SSRS.ps1

Finding NT user (Windows login) that uses SQL Server Login

As part of a security task I need to find all SQL Server logins that connect to the SQL server instance.
I create extended event for capture logins and filter only SQL Server logins.
The problem is that I can not tell from the SQL Server what was the NT user that was used.
Example:
From the xEvent I can see that user [sa] logged in to the SQL server instance and I can also see this client host name.
BUT , now I would like to know what was the domain account that was logged in to the client host name and use this SQL authentication.
I understand that SQL Server can not give this information but I would like yo know if I can get this info using PowerShell maybe.
I have the host name and the SID.
I could not find a solution here :
How to get Windows Log-in User Name for a SQL Log in User
You do not have a SID, that is a SQL Server SID (yes, there is a such a concept).
First, the answer: you do not. If you want to prevent SQL Logins, you deactivate SQL Logins, and that should be the end of the story.
Since there is no NTLM/Kerberos exchange for a SQL Server login, there is no way to find the credentials of the process/thread that initiated a SQL Login connection. However, you do have the host from where the connection was initiated and the process ID (they are the host_name and host_process_id columns in sys.dm_exec_sessions). Finding the credentials of the remote process is a trivial matter left as an exercise.
You've referenced having the SID, so if this is correct you can translate that to a user account. This works for both local users, and domain users:
$sid = 'S-1-5-21-3423846758-2645770820-3983523239-1001'
$objSID = New-Object System.Security.Principal.SecurityIdentifier($sid)
$objUser = $objSID.Translate( [System.Security.Principal.NTAccount])
($objUser.value -split '\\')[1]
Note: $objUser will contain either the computer name (for a local account) or the domain name (for an Active Directory account), so the split is to parse out the username only.
However, I'm currently unsure how you link this to which account they're using within SQL server (using SQL authentication) - I'm not sure where you're getting the SID information from (Windows event logs? Within SQL itself?).
Thank you all.
I managed to get the AD domain user by running a Get-WmiObject -Class Win32_Process :
1.Find the host_process_id and host_name using sys.dm_exec_sessions
2.Run a PowerShell:
Get-WmiObject -Class Win32_Process -ComputerName $host_name -Filter "ProcessId = '$($host_process_id )'" | ForEach-Object { $_.GetOwner() }

remote powershell script executed by anonymous user

We are running deployment scripts using pstrami. Part of the deployment is to execute database migrations. The migrations are using an connection string with Integrated Security.
When the script executes on the remote machine the migrations fail with a sql error saying Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'
The person executing the script is a domain administrator. Other deployments that we run execute the remote scripts with the user who started the process.
The problem is that the credentials are not hopping to SQL Server for integrated security. You need to do the following:
On the server (the one that is making the SQL Server connection, as administrator run:
Enable-WSManCredSSP -Role server
On the client machine, as administrator run:
Enable-WSManCredSSP -Role client -DelegateComputer YOUR_SERVER_NAME
To open this up to all servers, you can run:
Enable-WSManCredSSP -Role client -DelegateComputer *
Finally, your invoke command make sure you run -authentication credssp. An example:
invoke-command -computername $remoteServer -authentication credssp -scriptblock { write-host "hello!" } -credential $credentials
This is the scenario:
You run the pstrami(deployment) script from desktopA. The script pushes your installation files to serverA. Then on serverA the scripts are run remotely as the person inititating the script from desktopA. One of the steps is to run a sql database upate with fluentmigrator using a connection string paramter using "integrated security" and the database is on serverB.
Connection string example:
$migration_db_connection = Data Source=serverB;Initial Catalog=PropertyDb;Integrated Security=SSPI;
.\migrate.exe /conn "$migration_db_connection" /db SqlServer /a $migration_assembly /profile DEBUG
Pstrami uses the powershell command invoke-command which uses the account you are running the script under as the default user. So, what happens is that when you run the script from desktopA as "jonDoe" it then authenticates on serverA. So your pstrami scripts run under "jonDoe" on serverA. When you execute the fluentmigrator script on serverA as "jonDoe", fluentmigrator returns an error Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'. In IIS, you run into an interesting situation when you need to access another resource off of the IIS server and certain fairly common situations occur. When using Integrated Security, anonymous access is disabled, and impersonation is turned on, a Windows security measure kicks in and doesn't allow your site to access resources on any network servers. (http://weblogs.asp.net/owscott/archive/2008/08/22/iis-windows-authentication-and-the-double-hop-issue.aspx)
This is how I got around the Windows Authentication and the Double Hop problem I ran into. Run your migration scripts directly on your sql database server and include it as a server target in your pstrami environments.
Example:
Environment "dev" -servers #(
Server "serverA" #("InstallWeb")
Server "serverB" #("RunMigrations")
)
More on Double Hop
http://www.spdoctor.net/Pages/message.aspx?name=login-failed-for-user-bdc
http://www.sqlservercentral.com/blogs/sqlsandwiches/2011/06/20/double-hop-of-doom/
I am not able to comment on your question and posting this as an answer. I will update the same later.
It may be due to SQL Server not having the login account for your windows login account. If that is the problem please add the logged in user to the SQL Server in the remote machine.
If this is already addressed, then you have the option of giving Rights as DB_Owner to " NT AUTHORITY\ANONYMOUS LOGON " on the SQL Server as well as on the specific database you are using.

Resources