How to Restart SQL Reporting Service with Account and Password? - sql-server

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

Related

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

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() }

Remotely joining computer to domain using powershell and WMI

For a CI/CD environment I am building a PowerShell script to create an new Hyper-V VM which is basically a clone of a 'base-vm'. This base-vm is not a member of the domain, it is a Windows workgroup member.
When trying to add the computer to the domain I have the following issue, the script displayed below works when run directly on the target machine which is the Hyper-V host (running under an administrative account) but not when being run from the build server (Jenkins).
The process is as shown in the following scheme:
And the script part which is failing is the following:
Invoke-Command -Session $remoteSession -Scriptblock {
Rename-Computer -NewName $args[0] -Restart
} -ArgumentList $vmSettings.ComputerName
Start-Sleep -s 30
$newVmRemoteSession = New-PSSession -ComputerName $vmSettings.ComputerName -Credential $credentials
Invoke-Command -Session $newVmRemoteSession -Scriptblock {
Add-Computer -Domainname myfunny.domain -Credential $args[0] -Restart
} -ArgumentList $domainAdminCredentials
Remove-PSSession $newVmRemoteSession
Remove-PSSession $remoteSession
Write-Host "Done creating new VM"
The $remoteSession variable contains a remote PowerShell session based on the local administrator crendentials.
The $newVmRemoteSession variable contains an remote session to the renamed virtual machine with the local administrator crendentials.
The error I recieve while running this script via a build-job:
[base-vm] Connecting to remote server base-vm failed with the following error message : WinRM cannot complete the operation. Verify that the specified computer name is valid, that the computer is accessible over the network, and that a firewall exception for the WinRM service is enabled and allows access from this computer. By default, the WinRM firewall exception for public profiles limits access to remote computers within the same local subnet. For more information, see the about_Remote_Troubleshooting Help topic.
The command which throws the exception is:
Invoke-Command -Session $newVmRemoteSession -Scriptblock {
Add-Computer -Domainname myfunny.domain -Credential $args[0] -Restart
} -ArgumentList $domainAdminCredentials`
I have been looking for the solution for this problem, but I cannot find the error. First I thought it had to do with trusted relationships between the build server and the virtual machine but when I used WinRM to add that relationship the build still fails.
I used: winrm s winrm/config/client '#{TrustedHosts="*"}' to add the relationship.
UPDATE: The other thing I did is running the script with the same user as the build server did. This gave me the same error as above. The strange thing is that the user is an local administrator on the server from which the script is being run and is also member of the 'remote management users' group on that server.
UPDATE2: I found out that the issue has to do with Kerberos versus Negotiate authentication. When running a script from a domain joined workstation the script runs under the Kerberos scheme by default and when run from a standalone workstation it runs under the Negotaite scheme, which needs an SPN for what I read from https://msdn.microsoft.com/en-us/library/windows/desktop/aa378748(v=vs.85).aspx.
You're right in that it's probably an auth issue.
PowerShell uses Kerberos for this stuff and is set up for domain joined stuff.
I think you were on the right lines with the trusted hosts addition...
There's an article at http://powershell.com/cs/blogs/tips/archive/2016/01/25/enabling-powershell-remoting-with-ntlm.aspx, which explains how to set it up and uses slightly different syntax to what you've described. Maybe try that?
The computer was not accessible through the domain, so I used CredSSP to connect to it. To enable credssp I had to run the enable-wsmancredssp commandlet on the client and server and had to use the gpedit.msc addin to configure access.

SQL Server Agent run powershell file not found

I created a SQL Server Agent job and here is the job detail.
The job owner is my windows domain login.
The type is OS (cmdExec)
Run as SQL Server Agent Service Account
Command:
powershell.exe -executionpolicy bypass -file "D:\MyFolder\myFile.ps1".
When I ran the job it returned an error stating "D:\MyFolder\myFile.ps1" does not exist.
When I run the same command from cmd prompt it works find.
My question is what can I do to make SQL Server Agent Service Account "see" the file?
Thanks,
It's a privilege issue. I just granted read/execute permission to the Network Service login which SQL Server Agent uses.
It works now.
And thanks for all your responses.

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