notAChance
notAChance

Reputation: 1430

Powershell strange parameter behaviour

To start off, I'm just going to paste the result of $PSVersionTable.PSVersion as, apparantly, it shows the version of powershell...

You are now entering PowerShell : <name>
PS D:\aDirectory> $PSVersionTable.PSVersion

Major  Minor  Build  Revision
-----  -----  -----  --------
4      0      -1     -1

Below I have a function, DoSomeSqlForMe, which defines two parameters, $sql and $logFile.

When function is called, $sql is passed into it. $logFile is inherited from a parent script (but may also be passed in).

function DoSomeSqlForMe
{
    param
    (
        [string]$sql,
        [string]$logFile
    )

    #Do some stuff with $sql and $logfile
}

EDIT - function is being called as below (this is a direct copy + typical of other calls to same function):

DoSomeSqlForMe $sql

My issue is when $logFile is set as a parameter but not passed in when method is called ($logFile is still available as an inherited var) I get Exception message : The argument is null or empty.

However when I simply remove $logFile as a parameter, my log file is filled with what looks to me (uneducated in eastern languages) like Mandarin - 渮浡 repeated over and over again.

Any ideas?

Upvotes: 0

Views: 70

Answers (1)

rufer7
rufer7

Reputation: 4119

The problem is, that if you don't provide $logFile parameter when calling the function (i.e. DoSomeSqlForMe $arbitrarySql) by default $null gets assigned to $logFile parameter. To assign the before defined $logFile variable by default to the function parameter you have to adjust your function as follows.

function DoSomeSqlForMe
{
    param
    (
        [string]$sql,
        [string]$logFile = $logFile
    )

    #Do some stuff with $sql and $logfile
}

However I suggest to instead call your function with two parameters (i.e. DoSomeSqlForMe -sql $arbitrarySql -logFile $logFile)

Upvotes: 1

Related Questions