Forum Discussion

SBVRaja's avatar
SBVRaja
Copper Contributor
Dec 06, 2019
Solved

Return command is not coming out of function and not returning value

I am using below code 1) To verify whether given input text is in JSON format then 2) User acceptance on the file selected as per its version.   Means, if i give wrong JSON format in the input f...
  • JRCigars's avatar
    Dec 10, 2019

    SBVRaja I several gotchas which may explain the behavior you're seeing...

     

    • Using recursive calls to CFile is probably not the best approach, especially from inside the catch {} block.
    • The $Done variable is never properly initialized, and the only possible return value is "Good job" for $Required.
    • I might recommend moving any statements referencing $JSONformat inside your try {} block.
    • Your $title argument to the CFile function is never used.
    • If possible, avoid using Write-Host; and instead try using either Write-Verbose, Write-Output, Write-Information, Write-Warning, etc.
    • Since your Switch() statement only handles 2 conditions, an if() {} else {} block might be cleaner.
    • Return($Done) is mostly equivalent to: $Done; Return; Since this is the last statement in your function, Return is really unnecessary.

    That said, here's one possible re-write:

     

    function Cfile
    {
    	[cmdletbinding()]
    	param([string]$title = 'Enter the path of the file')
    	
    	begin {
    		$done = 'Bad job'
    	}
    	
    	process {
    		Do {
    			try {
    				$filepath = Read-host $title
    				$JSONformat = (get-content -Path $filepath -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop)
    				Write-Verbose "Valid JSON format`nEntered baseline version is: $($JSONformat.version)"
    			} catch {
    				Write-Warning 'Missing file, or provided text is not a valid JSON string'
    			}
    
    			$confirm = Read-Host 'Is that correct?? (Y/N)'
    			if ('Y' -eq $confirm) {
    				$done = 'Good job'
    			} else {
    				$title = 'Select Correct Config file'
    			}
    		} Until ('Bad job' -ne $done)
    	
    		$done
    	}
    	
    	end {}
    }
    
    $Required = Cfile -Verbose
    Write-Output $Required

     

    Hope this helps.

Resources