powershell unable to recognize parameter - sql

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

Related

How to use App Pool Identity to connect using SqlClient in Powershell?

We have many servers with a ASP.Net application installed. I'm trying to figure out a automatic way to connect to the sql server using Powershell.
They use a domain account to run the app pool. I have the code below to get the connection string from the app and the app pool identity to try to open a connection to sql.
However, when I run it in powershell, the sql login fails for, Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'. I don't understand why. I confirmed the ASP.Net Application is using the App Pool Identity in SQL via sp_who2.
Output confirms that the invoke-command is using the App Pool Identity. I can't change the connectionstring per business policies. I want to only use .Net to connect to SQL because I know .Net framework 4.8 will be on all machines I use to run it.
I removed the code for getting the connection string and app pool identity from the sample below in hopes to allow more people to troubleshoot.
Just update the username, password, and server name below and try it out
$username = 'MyUsername'
$password = 'MyPassword'
$ConnStr = 'Data Source=MyServer;Trusted_Connection=yes;'
$query = 'Select system_user, ##servername DBHostName,(SELECT login_time FROM sys.sysprocesses where spid=1)SQLUptime, ##version SQLVersion;'
$SQLPoshCmds = {
$env:USERNAME
$args[0]
try{
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = $args[0]
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $args[1]
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$SqlConnection.open()
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$DataSet.Tables|fl
}
Catch{
$_
# write "`r`n$($_.Exception)"
# write $_.ScriptStackTrace
# write $_.ErrorDetails
}
Finally{
$SqlConnection.Close()
$SqlConnection.Dispose()
}
}
if($ConnStr.Contains('Trusted_Connection=yes;')){
invoke-command -ArgumentList $ConnStr,$query -ComputerName '.' -ScriptBlock $SQLPoshCmds -Credential (New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username,(ConvertTo-SecureString -AsPlainText $password -Force))
}else{
invoke-command -NoNewScope -ScriptBlock $SQLPoshCmds
}

Unable to connect to SQL server via PowerShell using secure password

I'm trying to connect to SQL server via PowerShell using the below (I'm new to this). I always get the error "login failed" when I use secure password (from Get-Credential or password stored in file). But if I pass the password as plaintext instead of secure string, it connects successfully. Could any one please suggest a method to pass secure password, ideally stored in an external file.
The code I ran and the error is below:
$cred = Get-Credential
$pwd = $cred.Password
$uid = $cred.UserName
$SQLServer = "."
$SQLDBName = "TestDB"
#Initialize connection string
$connString = "Data Source=$SQLServer;Database=$SQLDBName;User ID=$uid;Password=$pwd"
#Create a SQL connection object
$conn = New-Object System.Data.SqlClient.SqlConnection $connString
#Attempt to open the connection
$conn.Open()
if($conn.State -eq "Open")
{
# We have a successful connection here
# Notify of successful connection
Write-Host "Test connection successful"
$conn.Close()
}
Exception calling "Open" with "0" argument(s): "Login failed for user 'TestUser'."
At line:18 char:1
+ $conn.Open()
+ ~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SqlException
Further details of error from SQL server:
Login failed for user 'TestUser'. Reason: Password did not match that for the login provided. [CLIENT: <local machine>]
Change this
$pwd = $cred.Password
to this
$pwd = $cred.GetNetworkCredential().Password
However, I would advise against storing a plain text password in memory like this. Your method requires it to--at best--be passed as a parameter in plain text, so you need a better method.
Try using this sqlserver module which supports the -Credential parameter in the Invoke-Sqlcmd function.
I was able to pass secure string as password by adding Integrated Security = True; parameter in connection string.
Thank you.

Diagnose SQL running from Power Shell

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.

trying to connect to SQL using Get-Credential in Winpe

Does anyone know how to pass Get-Credentials to a SQL login using powershell?
I have tried many different ways but no success.
This needs to run in winpe - i can get the credentials using Get-Credential but i need to use those to connect to SQL DB - i keep getting.
Login failed for 'NT AUTHORITY\ANONYMOUS LOGIN' The below code works fine in Windows - I am logged on as the user though so it must not be passing the credentials. if i remove the trusted_connection=true; i get the failed login and this is the best test for WINPE as no one is logged on. Is there a way to pass those Get-Credentials to SQL?
Either that or the same code does not work in WINPE - not sure why though?
$Cred = Get-Credential
Function SQL_CONNECT ($Query){
$ConnectionString = "server=VM855;database=LDMS2016;user id=$Cred.Username;password=$Cred.Password;trusted_connection=true;"
$SqlConnection = New-Object System.Data.SQLClient.SQLConnection($ConnectionString)
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.Connection = $SqlConnection
$SqlCmd.CommandText = $Query
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$a = $SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$DataSet.Tables[0]
}
$Owners = SQL_CONNECT "Select Task_Name, Task_owner, first_action_query_date from PROV_HISTORY_TASK" | Select-Object Task_Owner, first_action_query_date
$Owners
SQL connections use either:
Windows Authentication ("Trusted_Connection=True")
or
SQL Authentication ("User Id=myUsername;Password=myPassword;")
You cannot have both "Trusted_Connection" and "User ID/Password", you have to pick one.
In order to use Windows Authentication, the PowerShell process must be running as the user that has access to the database. i.e. you have to launch the PowerShell process as impersonating that user, and run your code.
Rough example will look something like this:
# Get the other user's credentials
$credential = Get-Credential
# Execute a scriptblock as another user
$commands = #'
#....code....
$ConnectionString = "server=VM855;database=LDMS2016;trusted_connection=true;"
#.....etc....
'#
Start-Process -FilePath Powershell.exe -LoadUserProfile -Credential $credential -ArgumentList '-Command', $commands
Or, the easier method is to just use SQL authentication, and hard code the username/password.
$ConnectionString = "server=VM855;database=LDMS2016;user id=Username;password=Password;"
Or at the very least you will have to use Read-Host to read in the username and password because $Cred.Password returns System.Security.SecureString and not the password in plain text.
For ex.
$Username = Read-Host "User:"
$Password = Read-Host "Password:"
$ConnectionString = "server=VM855;database=LDMS2016;user id=$Username;password=$Password;"

Authentication error with webclient in powershell

I'm relatively new to Powershell so really not sure where to go with this issue now. I am trying to download a file from a subversion repository and am getting the (401) Unauthorized" error. I am able to log into the site and download the file using IE using the exact Same credentials on the same machine.
$source = "http://repository/folder/File.exe"
$destination = "E:\Temp\File.exe"
$wc = New-Object System.Net.WebClient
$user="user"
$pwd=convertto-securestring -string "password" -AsPlainText -force
$creds=New-Object System.Management.Automation.PSCredential -ArgumentList $user, $pwd
$wc.Credentials = New-Object System.Net.NetworkCredential ($user, $Creds.GetNetworkCredential().Password,"DOMAIN")
$download=$wc.DownloadFile($source, "$destination")
Exception calling "DownloadFile" with "2" argument(s): "The remote server returned an error: (401) Unauthorized."
Any ideas if this is cross platform issue? And how to get around this?
Thanks
Are you using basic auth on your iis/apache? If so try this:
$source = "http://repository/folder/File.exe"
$destination = "E:\Temp\File.exe"
$wc = new-object System.Net.WebClient
$credCache = new-object System.Net.CredentialCache
$creds = new-object System.Net.NetworkCredential($user,$pwd)
$credCache.Add($source, "Basic", $creds)
$wc.Credentials = $credCache
$wc.DownloadFile($source, $destination)