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!
Related
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}
I am trying to run a SQL from Power Shell(which is on my windows 7 64 bit desktop) and the remote database host is MS SQL Server 2012.
The code is:
$Server= ".\DB_HOST_NAME"
$Database = "master"
$UserSqlQuery= $("select count(*) from [master].[sys].[some_table]")
# executes a query and populates the $datatable with the data
function ExecuteSqlQuery ($Server, $Database, $SQLQuery) {
$Datatable = New-Object System.Data.DataTable
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "server='$Server';database='$Database';trusted_connection=true;"
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
$Command.CommandText = $SQLQuery
$Reader = $Command.ExecuteReader()
$Datatable.Load($Reader)
$Connection.Close()
$Datatable
return $Datatable
}
# declaration not necessary, but good practice
$resultsDataTable = New-Object System.Data.DataTable
$resultsDataTable = ExecuteSqlQuery $Server $Database $UserSqlQuery
Write-Host "Statistic: " $resultsDataTable
Write-Host "Message: Transaction Delay is " $resultsDataTable.Rows.Count
When I run this from Windows PowerShell, I get following errors:
Exception calling "Open" with "0" argument(s): "A network-related or
instance-specific error occurred while establishing a connection to
SQL Server. The server 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: SQL Network Interfaces, error: 26
- Error Locating Server/Instance Specified)" At H:\test2.ps1:11 char:5
+ $Connection.Open()
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SqlException
Exception calling "ExecuteReader" with "0" argument(s): "ExecuteReader
requires an open and available Connection. The connection's current
state is closed." At H:\test2.ps1:15 char:5
+ $Reader = $Command.ExecuteReader()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : InvalidOperationException
Exception calling "Load" with "1" argument(s): "Value cannot be null.
Parameter name: dataReader" At H:\test2.ps1:16 char:5
+ $Datatable.Load($Reader)
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentNullException
So the first error is at $Connection.Open() but I don't know anything about power shell to figure out what is wrong. I have tried running the same SQL on the same DB host and it does return a number.
Can I get some help to know what am I doing wrong here?
This code:
$Server= ".\DB_HOST_NAME"
should be:
$Server= "DB_HOST_NAME"
The specification ".\DB_HOST_NAME" is interpreted as a named instance (DB_HOST_NAME) running on your local box.
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 follow this article to expand a variable in a scriptblock
My code tries this:
$exe = "setup.exe"
invoke-command -ComputerName $j -Credential $credentials -ScriptBlock {cmd /c 'C:\share\[scriptblock]::Create($exe)'}
How to fix the error:
The filename, directory name, or volume label syntax is incorrect.
+ CategoryInfo : NotSpecified: (The filename, d...x is incorrect.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName : remote_computer
You definitely don't need to create a new script block for this scenario, see Bruce's comment at the bottom of the linked article for some good reasons why you shouldn't.
Bruce mentions passing parameters to a script block and that works well in this scenario:
$exe = 'setup.exe'
invoke-command -ComputerName $j -Credential $credentials -ScriptBlock { param($exe) & "C:\share\$exe" } -ArgumentList $exe
In PowerShell V3, there is an even easier way to pass parameters via Invoke-Command:
$exe = 'setup.exe'
invoke-command -ComputerName $j -Credential $credentials -ScriptBlock { & "C:\share\$using:exe" }
Note that PowerShell runs exe files just fine, there's usually no reason to run cmd first.
To follow the article, you want to make sure to leverage PowerShell's ability to expand variables in a string and then use [ScriptBlock]::Create() which takes a string to create a new ScriptBlock. What you are currently attempting is to generate a ScriptBlock within a ScriptBlock, which isn't going to work. It should look a little more like this:
$exe = 'setup.exe'
# The below line should expand the variable as needed
[String]$cmd = "cmd /c 'C:\share\$exe'"
# The below line creates the script block to pass in Invoke-Command
[ScriptBlock]$sb = [ScriptBlock]::Create($cmd)
Invoke-Command -ComputerName $j -Credential $credentials -ScriptBlock $sb
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")