简体   繁体   中英

In Powershell set-variable not overriding Script Parameters? Trying to read JSON and override script parameters using JSON

I'm wondering about the following code. I use powershell to load the following json file called "tool.json":

{
  "1": {
    "Tool":           ["vhdl_component_packager"],
    "Name":           ["a1_stuff"],
    "Dir":            ["./source"],
    "Recurse":        ["true"],
    "ExcludeVhd":     ["*_tb.vhd"],
    "ExcludeEntity":  []
  }
}

Then when I execute my script I would expect the script to read the variables in the JSON file to override the parameters of the script, namely $Dir, and set it to ./source as shown in the JSON file. But that's not happening, instead its not change $Dir... I'm wondering how to fix it.


param(
    [string]$Dir = "."
)
function read_tool_json {
    $tool_json = "./tool.json"
    
    if (-not(test-path $tool_json)) {
        throw "Missing ./tool.json file"
    }       
    
    write-host "Reading file: $tool_json"
    $tool_json  = Get-Content -Raw $tool_json | ConvertFrom-Json
    
    foreach ($item1 in $tool_json.psobject.Properties) {
        write-host $item1.Name
        $top_name = $item1.Name
        $top_node = $tool_json.$top_name                
        foreach ($item2 in $top_node.psobject.Properties) {
           $elem_name = $item2.Name
           $elem_node = [array]$top_node.$elem_name             
           write-host "set-variable -name $elem_name -value $elem_node -scope global"
           set-variable -name $elem_name -value $elem_node -scope global -force
           $dir
        }           
    }       
}

read_tool_json

$script:Dir.GetType()

#QUESTION: how to get $script:Dir to equal "./source" from json file???
write-host "dir:($Dir)"

You've got a variable already defined at script scope called Dir :

param(
    [string]$Dir = "."
)

However, you are setting $Dir at global scope in your set-variable . You can see that if you add the following line to your script:

write-host "dir:($global:Dir)"

If you want to modify the the $Dir at script scope, then just remove the -scope global from your set-variable command, or change it to -scope script .

If you want to modify the the variable at script scope and also have it available at global scope, you'll have to do it explicitly at the end of your script:

$Dir = $global:Dir

Basciacally, you have 2 different variables here $global:Dir and $script:Dir .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM