I try to run the following command:
$serverName = 'firjt6'
Invoke-DbaQuery -SqlInstance 'some site' -Database 'CM_IDC' -Query $query -SqlParameters #{SrvName = $serverName}
And I keep on getting the following error:
[Invoke-DbaQuery] Failure | The wait operation timed out
Does anyone know where should I add the command TimeOut property?
$serverName = 'firjt6'
Invoke-DbaQuery -SqlInstance 'some site' -Database 'CM_IDC' -Query $query -SqlParameters #{SrvName = $serverName}
Related
i need to query database in an azure pipeline to find out when was the last login to an environment and if it is more than 2 weeks destroy the environment. to do that i used the below task. but i dont know how can i store the variable to use in the next task. can someone please help me?
- task: SqlAzureDacpacDeployment#1
inputs:
azureSubscription: ' A Service Connection'
AuthenticationType: 'servicePrincipal'
ServerName: 'myserver.database.windows.net'
DatabaseName: 'mydb'
deployType: 'InlineSqlTask'
SqlInline: |
DECLARE #LastLoginDate AS NVARCHAR(50)
SELECT #LastLoginDate = [LastLoginDate]
FROM [dbo].[AspNetUsers]
WHERE UserName <> 'system'
PRINT #LAstLoginDate
IpDetectionMethod: 'AutoDetect'
SQLInlineTask meant for execution of SQL Script on database.
Setting Variables in Pipeline Tasks available with either Bash or PowerShell.
PowerShell Script Task
$query = "DECLARE #LastLoginDate AS NVARCHAR(50)
SELECT #LastLoginDate = [LastLoginDate]
FROM [dbo].[AspNetUsers]
WHERE UserName <> 'system'
PRINT #LAstLoginDate"
# If ARM Connection used with service connection, ignore getting access token
$clientid = "<client id>" # Store in Variable Groups
$tenantid = "<tenant id>" # Store in Variable Groups
$secret = "<client secret>" # Store in Variable Groups
$request = Invoke-RestMethod -Method POST -Uri "https://login.microsoftonline.com/$tenantid/oauth2/token"
-Body #{ resource="https://database.windows.net/"; grant_type="client_credentials"; client_id=$clientid; client_secret=$secret }
-ContentType "application/x-www-form-urlencoded"
$access_token = $request.access_token
# If ARM connection used with service connection, ignore AccessToken Parameter
$sqlOutput = Invoke-Sqlcmd -ServerInstance $.database.windows.net -Database db$ -AccessToken $access_token -query $query
Write-Host "##vso[task.setvariable variable=<variable name>;]$sqlOutput"
Bash
echo "##vso[task.setvariable variable=<variable name>;isOutput=true]<variable value>"
Within same job and different tasks, access it using $(<variable name>)
In Different job, access it using $[ dependencies.<firstjob name>.outputs['mystep.<variable name>'] ]
References:
https://learn.microsoft.com/en-us/azure/devops/pipelines/process/set-variables-scripts?view=azure-devops&tabs=bash
https://medium.com/microsoftazure/how-to-pass-variables-in-azure-pipelines-yaml-tasks-5c81c5d31763
- task: PowerShell#2
inputs:
targetType: 'inline'
script: |
$LoginDate=(Sqlcmd myserver -U $(Username) -P $(Password) -d mydatabase -q "SET NOCOUNT ON; SELECT LastLoginDate=min(LastLoginDate) FROM mytable WHERE UserName<>'system';")
$Last=$LoginDate[2].trimstart()
Write-host $Last
Write-host "##vso[task.setvariable variable=LastLoginDate]$Last"
I am in need of some help folks. We are trying to get our SQL Vulnerability Assessment to be done via batch in PowerShell. I'm having some issues setting it all up though and am hoping someone can help me out.
I've tried a few different things but end of the day, I am still getting this error:
Invoke-SqlVulnerabilityAssessmentScan : SetParent failed for Database '[master]'.
At line:1 char:1
+ Invoke-SqlVulnerabilityAssessmentScan -Credential $cred -ServerInstan ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Invoke-SqlVulnerabilityAssessmentScan], FailedOperationException
+ FullyQualifiedErrorId : Microsoft.SqlServer.Management.Smo.FailedOperationException,Microsoft.SqlServer.Management.PowerShell.VulnerabilityAssessment.InvokeVulnerabilityAssessmentScan
$cred = Get-Credential
$instance = "server\sqldb"
Invoke-SqlVulnerabilityAssessmentScan -Credential $cred -ServerInstance $srv -DatabaseName "master"
I also tried this:
$cred = Get-Credential
$instance = "server\sqldb"
$srv = New-Object Microsoft.SqlServer.Management.Smo.Server -argumentlist $instance
$db = New-Object Microsoft.SqlServer.Management.Smo.Database -argumentlist $srv, "master"
Invoke-SqlVulnerabilityAssessmentScan -Credential $cred -ServerInstance $srv -DatabaseName $db
but still gives me the same result.
Any help with this is immensely appreciated!
I am working on powershell script for connecting to server. If I am passing server name inside script without param it's working, but if I am using input as server name it is saying "server not found". See script below:
clear
#param([string]$servername)
$filePath = "c:\temp\result.txt"
$Servername= "cx-siscsqltest\sqlinst"
#$SqlQuery = "select SUBSTRING(CONVERT(sysname, SERVERPROPERTY('ProductVersion')),0,CHARINDEX('.',convert(sysname,SERVERPROPERTY('ProductVersion')),0)) as
#'ProductVer';"
$SqlQuery="select * from sys.sysaltfiles"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = '$Servername'; Database = master; Integrated Security = SSPI;"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$DataSet.Tables[0] | out-file "C:\temp\version.csv"
#$version=System.Data.DataSet.Tables[0].Rows[0][0]
write-host $version
Above code works well without parameters, if I take servername as parameter i get the following errors:
The term 'param' is not recognized as the name of a cmdlet, function, script fi
le, or operable program. Check the spelling of the name, or if a path was inclu
ded, verify that the path is correct and try again.
At D:\sysdba\install_sp.ps1:4 char:6
+ param <<<< ([string]$servername)
+ CategoryInfo : ObjectNotFound: (param:String) [], CommandNotFou
ndException
+ FullyQualifiedErrorId : CommandNotFoundException
Exception calling "Fill" with "1" argument(s): "A network-related or instance-s
pecific error occurred while establishing a connection to SQL Server. The serve
r was not found or was not accessible. Verify that the instance name is correct
and that SQL Server is configured to allow remote connections. (provider: Name
d Pipes Provider, error: 40 - Could not open a connection to SQL Server)"
At D:\sysdba\install_sp.ps1:25 char:17
+ $SqlAdapter.Fill <<<< ($DataSet)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
Can you please help me out?
Param() must be the first line in your script. Remove the clear and you will see in your ISE that the colour of param() will change
I am trying to catch the exceptions generated in the SQL query execution result in my log file using powershell script.
But however the code that I use below catches the exceptions in the syntax of my powershell script and not the SQL returned exceptions.
Also I would like to log the result set of my SQL script upon successful execution. How can I acheive this.
The following is my PowerShell script,
try
{
if($Windows_authentication.tostring() -eq "1"){
invoke-SqlCmd -inputfile $Script_path\script.SQL -serverinstance $Ser_name -database $Db_name -querytimeout 65535 }
else
{
invoke-SqlCmd -inputfile $Script_path\script.SQL -serverinstance $Ser_name -database $Db_name -username $Userid -password $Passwd -querytimeout 65535 }
Write-Host "script.SQL Completed execution"
}
Catch
{
$ErrorMsg = $_.Exception.Message
Out-File -InputObject "The error message is - $ErrorMsg" -Append -NoClobber -FilePath "$Script_path\log.txt"
while( $ErrorMsg.InnerException ) {
$ErrorMsg = $ErrorMsg.InnerException
write-output $ErrorMsg
Out-File -InputObject "The error message is - $ErrorMsg" -Append -NoClobber -FilePath "$Script_path\log.txt"
}
break
}
Unless the exception being generated is caused on the Powershell / .Net side, the excepition handler doesn't process it. An example would be being unable to connect to the Sql Server. For any error in the TSQL code, error handling is done within Sql Server.
You can use try...catch in TSQL. There are more articles like Using TRY...CATCH in Transact-SQL and SO questions too.
I've written a powershell script that creates a new sql server database and login, and then sets the database owner to the newly created user. This is successful. However, I get a login failed exception when attempting to login within the same script. If I use SQL Server Management Studio the login works.
Here's the script:
$server = new-Object Microsoft.SqlServer.Management.Smo.Server("(local)")
$db = New-Object Microsoft.SqlServer.Management.Smo.Database($server, 'TestDB')
$db.Create()
$login = new-object Microsoft.SqlServer.Management.Smo.Login("(local)", 'TestUser')
$login.LoginType = 'SqlLogin'
$login.PasswordPolicyEnforced = $false
$login.PasswordExpirationEnabled = $false
$login.Create('Password1')
$server = new-Object Microsoft.SqlServer.Management.Smo.Server("(local)")
$db = New-Object Microsoft.SqlServer.Management.Smo.Database
$db = $server.Databases.Item('TestDB')
$db.SetOwner('TestUser', $TRUE)
$db.Alter()
Invoke-Sqlcmd -ServerInstance localhost -Database 'TestDB' -Username 'TestUser' -Password 'Password1' -Query "SELECT * FROM sysusers"
I've tried adding a Start-Sleep (up to 5mins) to no avail, and I've tried Restart-Service mssqlserver -Force, also to no avail.
Any ideas?
This isn't an answer to the problem I was encountering, just a work around. The script is being run as part of an automated deployment, the overall scripts are run under the "NT AUTHORITY\SYSTEM" username, so to get around my logging in issue I'm simply using Integrated Security=true.
I think your final line should read:
Invoke-Sqlcmd -ServerInstance '(local)' -Database 'TestDB' -Username 'TestUser' -Password 'Password1' -Query "SELECT * FROM sysusers"
Notice the use of '(local)' rather than 'localhost'.
follow the codes below
$SqlServer = "servar.site.com Or server ip with port"
$SqlDBName = "dbName"
$sqlConnection = New-Object Microsoft.SqlServer.Management.Common.ServerConnection
$sqlConnection.ServerInstance=$SqlServer
$sqlConnection.LoginSecure = $false
$sqlConnection.Login = "userid if you have"
$sqlConnection.Password = "password if is needed to connect to sql server"
Add-Type -Path "C:\Program Files\Microsoft SQL
Server\140\SDK\Assemblies\Microsoft.SqlServer.Smo.dll"
$server = New-Object Microsoft.SqlServer.Management.Smo.Server($sqlConnection)
# get all of the current logins and their types
$server.Logins |
Select-Object Name, LoginType, Parent
# create a new login by prompting for new credentials
$NewLoginCredentials = Get-Credential -Message "Enter credentials for the new login"
$NewLogin = New-Object Microsoft.SqlServer.Management.Smo.Login($server,
$NewLoginCredentials.UserName)
$NewLogin.LoginType = [Microsoft.SqlServer.Management.Smo.LoginType]::SqlLogin
$NewLogin.Create($NewLoginCredentials.Password)
# create a new database user for the newly created login
$NewUser = New-Object
Microsoft.SqlServer.Management.Smo.User($server.Databases[$SqlDBName],
$NewLoginCredentials.UserName)
$NewUser.Login = $NewLoginCredentials.UserName
$NewUser.Create()
$NewUser.AddToRole("db_datareader")