从文件加载PowerShell哈希表?
我有一个文件,其中包含一些PowerShell对象表示法中的数据:从文件加载PowerShell哈希表?,powershell,Powershell,我有一个文件,其中包含一些PowerShell对象表示法中的数据: @{ X = 'x'; Y = 'y' } 我想将其加载到文件中的一个变量中。(我在编写一个repo时计算出来) Get Content返回一个数组,其中包含文件中的行;输出字符串用于将它们连接在一起 调用表达式然后运行脚本,并捕获结果。这是开放的注射攻击,但在我的具体情况下,这是确定的 或者,如果您更喜欢PowerShell精简版: PS> $data = gc .\foo.pson | Out-String | ie
@{ X = 'x'; Y = 'y' }
我想将其加载到文件中的一个变量中。(我在编写一个repo时计算出来)
Get Content
返回一个数组,其中包含文件中的行;输出字符串
用于将它们连接在一起
调用表达式
然后运行脚本,并捕获结果。这是开放的注射攻击,但在我的具体情况下,这是确定的
或者,如果您更喜欢PowerShell精简版:
PS> $data = gc .\foo.pson | Out-String | iex
(我找不到较短形式的
输出字符串
)如果您可以为该文件提供扩展名.ps1
,例如,data.ps1
,则它不能比此代码简单:
$data = <path>\data.ps1
$data=\data.ps1
我使用了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函数我在使用@Chad建议的ConvertFrom StringData时遇到了麻烦。如果您这样做:
$hash = get-content .\test.txt | ConvertFrom-StringData
我发现我有一个对象数组而不是哈希表。事实上,我似乎有一个哈希表数组,每个哈希表都有一个条目。我用一句话确认:
$hash.GetType()
看起来您需要连接slurped输入文件的每一行,以确保它形成一个字符串供ConvertFrom.使用:
$hash = ((get-content .\test.txt) -join '`n') | ConvertFrom-StringData
这是一篇较老的文章,但是,这是对您已接受的解决方案的一种扭曲,也许更“安全”,请记住不受信任的文件 在笔记中,您有一个包含使用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文件)只是一个哈希表,因此此概念可能有助于您引入脚本块或其他内容
参考资料:从您拥有的PowerShell 5.0开始
Import-PowerShellDataFile
它从.psd1文件导入值。因此,您只需将文件重命名为*.psd1
官方帮助是。正确的(我没有意识到我不需要点源文件),但是看起来它可以直接运行,我并不特别想要。我在问题中没有提到它(为了简单起见),但文件实际上包含一个对象树:一个哈希表数组,包含其他数组和哈希表。可能这是Powershell 4,但我可以跳过字符串部分,只需执行:$hash=Get Content。\file.pson | Invoke expression您也可以只使用
Get Content-Raw。\test.txt
,它可以阻止文件逐行传输到ConvertFrom StringData
;对于一个散列数组,每一行是否都包含在@{}中,例如@{Z='Z';A='A'}?
Import-PowerShellDataFile