Search code examples
powershellusing

Error while implementing using in powershell


Following this post when I am trying to implement Using functionality in Powershell

Function cUsing {
    param (
        [System.IDisposable] $inputObject = $(throw "The parameter -inputObject is required."),
        [ScriptBlock] $scriptBlock = $(throw "The parameter -scriptBlock is required.")
    )
    Try { &$scriptBlock }
    Finally {
        if ($inputObject -ne $null) {
            if ($inputObject.psbase -eq $null) {
                $inputObject.Dispose()
            } else {
                $inputObject.psbase.Dispose()
            }
        }
    }
}


    cUsing($sqlConnection = New-Object System.Data.SqlClient.SqlConnection)
{
$sqlConnection.ConnectionString = "Server=myserver; Database=master; Integrated Security= True"
$sqlConnection.Open()
$sqlCmd = New-Object System.Data.SqlClient.SqlCommand
$sqlCmd.CommandText = "SELECT STATEMENT"
$sqlCmd.Connection = $sqlConnection
$dsValues = New-Object System.Data.DataSet
$daValues = New-Object System.Data.SqlClient.SqlDataAdapter($sqlCmd)
$daValues.Fill($dsValues)
Write-Host $dsValues.Tables[0]
}

Error:

[ScriptBlock] $scriptBlock = $(throw  <<<< "The parameter -scriptBlock is required.")

Edit [Graimer]

When I have moved the curly braces like below

cUsing($sqlConnection = New-Object System.Data.SqlClient.SqlConnection){
....
....
 Write-Host $dsValues.Tables[0]}

I am not getting any error but the output which I am getting is

    $sqlConnection.ConnectionString = "Server=myserver; Database=master; Integrated Security= True"
$sqlConnection.Open()
$sqlCmd = New-Object System.Data.SqlClient.SqlCommand
$sqlCmd.CommandText = "Select query"
$sqlCmd.Connection = $sqlConnection
$dsValues = New-Object System.Data.DataSet
$daValues = New-Object System.Data.SqlClient.SqlDataAdapter($sqlCmd)
$daValues.Fill($dsValues)
Write-Host $dsValues.Tables[0]

EDIT [Ansgar Wiechers]

when I have changed the scriptblock line to

Function cUsing {
param (
    [System.IDisposable] $inputObject = $(throw "The parameter -inputObject is required."),
    [ScriptBlock] $scriptBlock = ${throw "The parameter -scriptBlock is required."}
)

I am not getting any error but I am getting the same output which I have showed in Edit above.


Solution

  • The problem with your code is that you don't provide the scriptblock as a parameter, but as a command on it's own. Commands in Powershell are on a single line. Your code runs the command with only the using parameter, and fails. THEN you declare a scriptblock.

    You have two options here; escape the linebreak(BAD practice), or move the opening curly brace one line up so it is considered part of the cusing command. Like this:

    cUsing($sqlConnection = New-Object System.Data.SqlClient.SqlConnection) {
        $sqlConnection.ConnectionString = "Server=myserver; Database=master; Integrated Security= True"
    ...
    ..
    .
    }