Power shell脚本在Windows PowerShell ISE中运行良好,但在Power shell版本5中不起作用

问题描述 投票:3回答:1

我有以下脚本,它在ISE中工作正常。我可以通过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();  

但在PowerShell版本5中,结果是: -

提供的文本不是有效的JSON字符串

请注意,我在同一目录中有backup_settings.json。可能是什么原因?如何在电源外壳中运行此操作并获得正确的结果?

更新的代码和结果: -

我尝试了以下方法: -

    $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();

结果:-

   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
json shell powershell
1个回答
2
投票

在PowerShell中运行它时,听起来像JSON文件的路径未正确解析。添加以下内容以查看是否是这种情况:

Test-Path $global:file

如果它打印出False,那将意味着您的脚本无法找到json文件。在这种情况下,您应该将第一行更改为以下内容:

$file = (Join-Path $PSScriptRoot "backup_settings.json")
© www.soinside.com 2019 - 2024. All rights reserved.