masiboo
masiboo

Reputation: 4719

Power shell script works fine in Windows power shell ISE, but it done't work in Power shell version 5

I have following script it works fine in ISE. I can execute and debug this script by ISE.

    $file = "backup_settings.json";
    class JsonParser
    {
        $json = $null;
        $setting  = $null;
        $validJson = $false;
        $baseAddress = $null;

        JsonParser()
        {

        }

        ParseJson()
        {
            try 
            {
                $this.json = Get-Content -Raw $global:file; 
                $this.setting = ConvertFrom-Json $this.json -ErrorAction Stop;
                $this.validJson = $true;
            } 
            catch 
            {
                $this.validJson = $false;
            }

            if (-Not $this.validJson) 
            {
                Write-Host "Provided text is not a valid JSON string" -foregroundcolor "Red";
                return;
            }


            if($this.setting.baseAddress)
            {
                $this.baseAddress = $this.setting.baseAddress;
                Write-Host $this.baseAddress;
            }
            else
            {
                Write-Host "No valid baseAddress provided setting file" -foregroundcolor "Red";
                return;
            }
        }
    }

    $json = [JsonParser]::new(); 
    $json.ParseJson();  

But in PowerShell version 5 the result is:-

Provided text is not a valid JSON string

Note that I have backup_settings.json in the same directory. What could be the reason? How can I run this in power shell with correct result?

Updated code and result:-

I tried the following:-

    $file = (Join-Path $PSScriptRoot "backup_settings.json")

    Write-Host $file;

    if([String]::IsNullOrEmpty($file))
    {
        Write-Host "Empty path"  
    }
    else
    {
        Write-Host "file  path: "$file;
    }

    if(Test-Path $file)
    {
        Write-Host "File exist" $file.ToString();
    }
    else
    {
        Write-Host "file not found".
    }
    $json = [JsonParser]::new(); 
    $json.ParseJson();

Result:-

   C:\tools\backup_settings.json
  file  path:  C:\tools\backup_settings.json
  File exist C:\tools\backup_settings.json
  Provided text is not a valid JSON string

Upvotes: 3

Views: 62

Answers (1)

Nasir
Nasir

Reputation: 11431

Sounds like the path to your JSON file is not properly resolved when you're running it in powershell. Add the following to see if that's the case:

Test-Path $global:file

If it prints out False, that would mean that your script is not able to find the json file. In that case, you should probably change the first line to something like this:

$file = (Join-Path $PSScriptRoot "backup_settings.json")

Upvotes: 2

Related Questions