-1

I am facing a problem with a PowerShell variable.

My scenario is,

  • Inside a function, I declare a variable $a, than in a switch, I get a value and store this to variable $a.

  • Now in another switch in that function, I want to compare $a. But there $a returns null.

Sample code is given below:

function fun 
{

  [CmdletBinding()]
  Param (
    [Parameter(Mandatory = $true, Position = 0)]
    [ValidateNotNullOrEmpty()]
    $param       
   )

    $Get_OldData = " " #declare variable

    switch ($param){

        'param_001' {
            $Get_OldData = "test data returned"
        }

        Default {
            $Get_OldData = "test data returned"
        }
    }


    switch ($param){

        'param_001' {
            $New_Data = "New Data"

            #problem is here, can not compare $Get-OldData returns null here
            #though data is assigned 

            if ( $New_Data  -eq $Get_OldData){
                #logic goes here
            }
        }
        Default {
            $New_Data = "New Data"
        }
    }
}

What is the solution of this problem?

Eric Ipsum
  • 723
  • 3
  • 10
  • 24

1 Answers1

1

You have multiple issues with your code.

The main issue probably is that you are using $param within your switch which has not been set. Same applies to $Fetch. Another Issue is that your $New-Data variable contains a hypen which you either should replace with an underscore or surround with curly brackets like ${New-Data}.

Also, // does not introduce a comment, you have to use a hash #.

Martin Brandl
  • 56,134
  • 13
  • 133
  • 172