我发现 PowerShell 对我越来越有吸引力,因此我在终端上花费了大量时间。 我的个人资料中有许多哈希表,用于各种用途,但主要是为了将常用数据保存在我的手指下。
我这里有一个这样的哈希表:
$SYS = [Ordered]@{
Posh = "C:\Program Files\PowerShell\7\pwsh.exe"
ReflectLogs = Get-ChildItem -Path "C:\Users\All Users\Macrium\Reflect" -Filter *.html*
ShareXUploadHistory = Convertfrom-Json -Inputobject (Get-Content -Path "C:\Users\...\Documents\Sharex\History.Json")
}
ShareXUploadHistory
键从不断变化的文件中读取,我想重建该键,以便每次调用 $SYS.ShareXUploadHistory
json 数据将基于文件 History.Json
的最新状态,而不是加载我的 $Profile
时的状态。
我尝试了以下操作,但当我调用 $SYS.ShareXUploadHistory
时 key 未更新:
$SYS = [Ordered]@{
Posh = "C:\Program Files\PowerShell\7\pwsh.exe"
ReflectLogs = Get-ChildItem -Path "C:\Users\All Users\Macrium\Reflect" -Filter *.html*
ShareXUploadHistory = . {Convertfrom-Json -Inputobject (Get-Content -Path "C:\Users\...\Documents\Sharex\History.Json")}
}
最佳答案
一种方法是将其添加为 PSScriptProperty
,那么每次调用该成员 ($SYS.ShareXUploadHistory
) 时,都会重新评估该成员。缺点是,由于这是一个有序字典而不是 pscustomobject,因此您不会将其视为键。
$SYS = [ordered]@{
Posh = 'C:\Program Files\PowerShell\7\pwsh.exe'
ReflectLogs = Get-ChildItem -Path 'path\to\stuff' -Filter *.html*
}
$SYS.PSObject.Members.Add([psscriptproperty]::new(
'ShareXUploadHistory',
{ Get-Content 'path\to\Sharex\History.Json' -Raw | ConvertFrom-Json }))
$SYS
关于powershell - 如何在每次调用时重建哈希表的特定键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76434073/