PowerShell Hashtable无法正确返回

时间:2017-01-11 20:49:38

标签: powershell hashtable

我确信我之前没有任何问题,但现在我不知道发生了什么。

Script1.ps1

$Output = PowerShell.exe -File "C:\Temp1\Script2.ps1"
$Output.Value1

Script2.ps1

$HashTable = New-Object PSObject -Property @{
    "Value1" = "Data1"
    "Value2" = "Data2"
    "Value3" = "Data3"
}
return $HashTable

我期待得到一张干净的桌子,我可以从中提取数据,但我得到了这个:

screenshot

如果我只是自己运行Script2,我可以使用$HashTable.Value1但是将它返回到Script1似乎是一个问题。

3 个答案:

答案 0 :(得分:3)

当您运行PowerShell.exe时 - 您实际上正在调用外部命令,并且您获得的结果很可能是[System.Object[]]。您可以使用方法GetType轻松验证它:

$Output.GetType()

运行PowerShell脚本的方式是调用操作符(&)或点源操作符(.)。前者将在其自己的范围内运行一个脚本(因此脚本中定义的变量/函数不会泄漏"泄漏到父范围内)。后者将执行脚本,就好像它是父级的组成部分一样。在你的情况下,呼叫操作员应该做你需要的:

$Output = & "c:\temp\Script1.ps1"
# or - as there are no spaces in the path, so script acts as any other command...
$Output = c:\temp\Script1.ps1

这应该像预期的那样为您提供自定义对象。要获得哈希表 - 您不需要New-Object - 只需返回传递给该命令的Property参数的哈希表。

答案 1 :(得分:2)

您正在另一个PowerShell进程中运行Script2.ps1。像哈希表这样的PowerShell对象不会跨进程边界传输。而是将输出转换为字符串数组。

演示:

PS C:\> $Output = powershell.exe -File '.\test.ps1'
PS C:\> $Output

Value1              Value2              Value3
------              ------              ------
Data1               Data2               Data3


PS C:\> $Output.GetType().FullName
System.Object[]
PS C:\> $Output[0].GetType().FullName
System.String
PS C:\> $Output | % { '=' + $_.Trim() + '=' }
==
=Value1              Value2              Value3=
=------              ------              ------=
=Data1               Data2               Data3=
==
==

在当前的PowerShell流程中运行脚本(例如通过调用运算符)以避免这种情况:

PS C:\> $Output = & '.\test.ps1'
PS C:\> $Output

Value1              Value2              Value3
------              ------              ------
Data1               Data2               Data3


PS C:\> $Output.GetType().FullName
System.Management.Automation.PSCustomObject
PS C:\> $Output.Value1
Data1

旁注:正如您在问题的评论中指出@sodawillow,您正在创建自定义对象,而不是哈希表。

答案 2 :(得分:1)

同意sodawillow;只需使用:

[Hashtable] $HashTable = @{ 'Value1' = 'Data1';
                            'Value2' = 'Data2';
                            'Value3' = 'Data3'
                          }
return $HashTable;