Powershell script to find services running on remote servers - sql-server

Need a Powershell script to list out the services running on remote servers.
Is there any way to list out the name of services running on remote servers without logging in individually on remote servers and checking?

You could use the the following command and specify the remotesystem you would like to get the services from. The parameter ComputerName is a strin array. So you could pass more then one system to the command.
Get-Service -ComputerName $ComputerName
Get-Service -ComputerName ($ComputerName1, $ComputerName2)

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

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

(SQL Server 14) SQL Server WMI Provider is not available on <COMPUTER NAME>

I'm trying to enable the TCP/IP and Named Pipes Protocols using PowerShell, but I'm unable to due to the following error.
Here is the code I'm using to connect to the Server Protocols.
Is there a way to make SQL Server WMI available through PowerShell?
Here is what the $machine variable looks like after this cmdlet:
$machine = New-Object 'Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer' -ArgumentList 'STORE000013'
I think you are missing one... When running PowerShell (PowerShell.exe) instead of SQL Server PowerShell, first execute the following statements to manually load the required assemblies:
# Load the assemblies
[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlWmiManagement")
For more information, here:
https://technet.microsoft.com/en-us/library/dd206997(v=sql.105).aspx

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 cmdlet (sqlps) and remote server

I'm using sqlps powershell module to get some data from my local database. My code is something like this
PS C:\> Import-Module sqlps -DisableNameChecking
PS SQLSERVER:\> cd "SQL\myMachineName\..."
It works correctly, but sometimes I need to connect to a remote server running SQL server, so I use Enter-PSSession. Is this the correct way or can I somehow map that server under local SQLSERVER:\SQL directory?
The PowerShell provider for SQL server can be used to connect to a remote SQL server without PowerShell remoting. For example, at the SQLSERVER: drive, you can change the location to a different SQL Server using
PS SQLSERVER:\> cd "SQL\remoteMachineName\SQLInstanceName"

Resources