Error passing variables as parameters in powershell

Asked

Viewed 120 times

0

Hello

A Powershell script has the following code:

function GetPerfis
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$StartDate,
        [Parameter(Mandatory)]
        [string]$EndDate
    )
     $cmd = New-Object System.Data.SqlClient.SqlCommand
    $cmd.Connection = $conn
    $cmd.Transaction = $transaction

    LogWrite  "GetProfiles startDate: $startDate and endDate: $endDate"

    ....

}

$startDate = $args[0]
$endDate = $args[1]
LogWrite  "startDate: $startDate and endDate: $endDate"
$profiles = GetPerfis -StartDate $startDate -EndDate $endDate

Output in log:

startDate: 2014-01-01 and endDate: 2015-01-01
GetProfiles startDate: 2014-01-01 and endDate: 2015-01-01

Give me the following mistake:

System.Management.Automation.RuntimeException: You cannot call a method on a 
null-valued expression.

Any idea the reason for the mistake?

1 answer

1

This error can lead anywhere and it is not possible to notice this without knowing at least the number of the line where it happened.

Did System.Data.Sqlclient.Sqlcommand even load? check that $cmd is not $null after that new-Object

tip:

This form of receiving command line parameters is not robust at all. $args is the style of other programming languages and is not recommended in powershell. instead of:

$startDate = $args[0]
$endDate = $args[1]

what I recommend is that you delete those two lines and start the program with:

param (
   [string]$startDate = "2014-01-01",
   [string]$endDate = "2015-01-01"
)

so it is always easier to initialize the variables you receive from parameter, and you can then put value by omission, which helps others to understand what the code expects as parameter.

  • In this solution appears me the error: "The assignment Expression is not Valid. The input to an assignment Operator must be an Object that is Able to Accept assignments, such as a variable or a Property." Do you have any idea why?

  • Yes, the param() is to place before the remaining ps1 instructions. [https://www.red-gate.com/simple-talk/sysadmin/powershell/how-to-use-parameters-in-powershell/]

  • I already put at the beginning of the script but I still have the same error. It gives error in assigning the default value in the first parameter...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.