【问题标题】:How to pass hashtable to powershell script invocation如何将哈希表传递给powershell脚本调用
【发布时间】:2019-12-20 13:13:19
【问题描述】:

我的脚本接受两个参数,一个字符串arg1 和一个哈希表arg2

Script.ps1

Param(
        [string]$arg1,
        [hashtable]$arg2,
    )
Write-Host "@$(ConvertTo-Json $arg2)"

如何将字典从 powershell 传递到此脚本,方法是调用它以使其在单独的进程中运行。

Call.ps1

$d = @{a="bla"} 
$s = "@$((ConvertTo-Json $a -Compress) -replace ':','=')"
powershell -File Script.ps1 "-arg2 $s" # We need another process (no access to the variables in this script)

我不知道我做错了什么(见question),但这不起作用。或者还有其他的

【问题讨论】:

  • 可以把参数类型改成string吗?那么在不“脏”的情况下与 JSON 相互转换会很容易。

标签: powershell hashtable


【解决方案1】:

通过做:

$s = "@$((ConvertTo-Json $a -Compress) -replace ':','=')"

您将哈希表的值转换为字符串。所以你应该使用:

param(
[string]$arg1
[string]$arg2
)

现在您可以很容易地将 $arg2 转换为 JSON。

【讨论】:

    【解决方案2】:

    一直在摆弄这个,终于想出了这个:

    Script.ps1

    Param(
        [string]$arg1,
        [string]$arg2
    )
    
    $scriptBlock = [scriptblock]::Create($arg2)
    # check that $arg2 contains no other Powershell commands
    # see: https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.scriptblock.checkrestrictedlanguage?view=pscore-6.2.0
    $scriptBlock.CheckRestrictedLanguage([string[]]@(), [string[]]@(), $false)
    # execute it to create the hashtable
    $ht = ( & $scriptBlock )
    
    Write-Host "$(ConvertTo-Json $ht)"
    

    Call.ps1

    $d = @{'a'="bla"} 
    
    # convert to JSON, replace ':' by '=' and escape the quotes with a backslash
    $s = '@{0}' -f ((ConvertTo-Json $d -Compress) -replace ':','=' -replace '"', '\"')
    
    powershell -File Script.ps1 -arg2 $s
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-07
      • 2013-09-17
      • 1970-01-01
      • 2019-06-04
      • 2018-05-30
      • 2011-08-01
      相关资源
      最近更新 更多