powershell - 如何在每次调用时重建哈希表的特定键?

标签 powershell

我发现 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/

相关文章:

Powershell模板

PowerShell - 如何强制超时调用命令

c# - 在 C# 中,我们如何确定调用者是否使用 Windows PowerShell 5.1 或更高版本?

windows - 如何以编程方式模拟文件损坏以测试 ReFS 健康检查和恢复功能?

powershell - 如何将文件从旧的文件夹结构移到新的文件夹结构?

powershell - Docker 机器错误 : Hyper-V PowerShell Module is not available

powershell - Get-ChildItem 找不到路径,因为它不存在

c# - 'Microsoft.AspNet.Server.Kestrel' 不包含适合入口点的静态 'Main' 方法

iis - 我可以使用 PowerShell 而不是 AppCmd.exe 来监视 IIS 状态吗?

azure - 如何从 Azure PowerShell 为用户请求 Azure Graph API 访问 token ?