简体   繁体   中英

How do I pass parameters properly?

Please see my Function-to-be below:

Function Query {
    param (
        [string]$query
        [string]$server
        [string]$dbase
        [string]$user
        [string]$pass
    )

    if ($user) { 
        $connstr = "Server={0};Database={1};User ID={2};Password={3};Trusted_Connection=False;Connect Timeout=15" -f $server, $dbase, $user, $pass 
    } 
    else { 
        $connstr = "Server={0};Database={1};Integrated Security=True;Connect Timeout=15" -f $server, $dbase
    }
    $conn.ConnectionString = $connstr 


    switch ($query.Split()[0]) {
        "SELECT" {
            $cmd = New-Object System.Data.SqlClient.SqlCommand($query,$conn)
            $adapter = New-Object System.Data.SqlClient.SqlDataAdapter($cmd)
            $dataset = New-Object System.Data.DataSet
            $adapter.Fill($dataset) | Out-Null
            return $dataset
        }
        "UPDATE" {
            $cmd = New-Object System.Data.SqlClient.SqlCommand($query,$conn)
            return $cmd.ExecuteNonQuery()
        }
        "INSERT" {
            $cmd = New-Object System.Data.SqlClient.SqlCommand($query,$conn)
            return $cmd.ExecuteNonQuery()
        }
    }
}

Query -query "SELECT TOP 10 myField FROM myTable" -server "SQLEXPRESS" -dbase "TEST"

This doesn't work, Powershell ISE gives me red in the param section but I don't understand why. Because of the many different ways people seem to construct Powershell functions (I'm a beginner :)) I am somewhat confused.

How do I make this function work?

Put commas , between the parameters:

Function SomeName {
  Param ($param1,$param2,$param3)
}

etc. You can use whitespace or line break after the comma for readability, which is what most people do:

Function SomeName {
   param (
          $param1,
          $param2 
         )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM