从文件加载PowerShell哈希表?

时间:2012-05-24 19:14:57

标签: powershell

我有一个包含PowerShell Object Notation中的一些数据的文件:

@{ X = 'x'; Y = 'y' }

我想将其加载到文件中的变量中。

6 个答案:

答案 0 :(得分:19)

(我在把一个复制品放在一起时想出来了)

PS> $content = ( Get-Content .\foo.pson | Out-String )
PS> $data = ( Invoke-Expression $content )

Get-Content返回一个包含文件中行的数组; Out-String用于将它们连接在一起。

Invoke-Expression然后运行脚本,并捕获结果。这对注射攻击是开放的,但在这种情况下就可以了。

或者,如果您更喜欢PowerShell简洁:

PS> $data = gc .\foo.pson | Out-String | iex

(我找不到Out-String)的简短形式

答案 1 :(得分:7)

我使用过ConvertFrom-StringData。如果你想使用这种方法,你需要改变存储键/值对的方式,每个键都有自己的行,没有引号:

#Contents of test.txt
X = x
Y = y

get-content .\test.txt | ConvertFrom-StringData

Name                           Value
----                           -----
X                              x
Y                              y

ConvertFrom-StringData是一个内置的cmdlet。我在这里创建了相应的ConvertTo-StringData函数http://poshcode.org/1986

答案 2 :(得分:4)

如果您可以为此文件指定扩展名.ps1,例如data.ps1,那么它不能比此代码更简单:

$data = <path>\data.ps1

答案 3 :(得分:4)

我使用ConvertFrom-StringData遇到麻烦,因为@Chad建议。如果你这样做:

$hash = get-content .\test.txt | ConvertFrom-StringData

我发现我有一个对象数组而不是哈希表。实际上,似乎我有一个哈希表数组,每个哈希表都有一个条目。我确认:

$hash.GetType()

看起来你需要加入slurped输入文件的每一行,以确保它为ConvertFrom ..使用它形成一个字符串:

$hash = ((get-content .\test.txt) -join '`n') | ConvertFrom-StringData

答案 4 :(得分:1)

这是一篇较旧的文章,但是请记住不受信任的文件,这与您接受的解决方案有些不同,也许稍微更“安全”。

在笔记中,您有一个包含使用Powershell语法的哈希表的文件。有了该约束,您可以直接将其导入:

$HashPath = ".\foo.pson"
# input file contents
$filecontent = Get-Content -Path $HashPath -Raw -ErrorAction Stop
# put the file in a script block
$scriptBlock = [scriptblock]::Create( $filecontent )
#check that the file contains no other Powershell commands
$scriptBlock.CheckRestrictedLanguage( $allowedCommands, $allowedVariables, $true )
#execute it to create the hashtable 
$hashtable = ( & $scriptBlock ) 

请注意,$scriptBlock.CheckRestrictedLanguage可以替换为

$scriptBlock.CheckRestrictedLanguage([string[]]@(), [string[]]@(), $false)

使用一个空字符串列表,因此我们不允许任何Powershell命令。导入哈希表时,这正是我们想要的。最后一个是allowEnvironmentVariables,因此我们在此示例中将其限制为$false

旁注,Powershell模块(psd1文件)只是一个哈希表,因此此概念可以帮助您提取脚本块或其他内容。

参考:https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.scriptblock.checkrestrictedlanguage?view=powershellsdk-1.1.0

答案 5 :(得分:0)

从PowerShell 5.0开始

Import-PowerShellDataFile

从.psd1-文件导入值。因此,您唯一要做的就是将文件重命名为* .psd1

官方帮助是here