deepti
deepti

Reputation: 729

powershell unable to recognize parameter

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?

Upvotes: 1

Views: 2307

Answers (1)

guiwhatsthat
guiwhatsthat

Reputation: 2434

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

Upvotes: 2

Related Questions