如何用多级[PSCustomObject]批量创建PowerShell全局变量?
解决多级PSCustomObject提取字符串键值对并创建全局变量的PowerShell方案
完整修复后的函数代码
function ConvertTo-GlobalStringVariable { [CmdletBinding()] param( [Parameter(Mandatory, ValueFromPipeline)] [PSCustomObject]$InputObject, [string]$ExportJsonPath ) process { # 递归遍历PSCustomObject的属性 function Invoke-RecurseObject { param($Object, [string]$ParentKey = '') foreach ($prop in $Object.PSObject.Properties) { $currentKey = if ($ParentKey) { "$ParentKey.$($prop.Name)" } else { $prop.Name } if ($prop.Value -is [PSCustomObject]) { # 递归处理嵌套对象 Invoke-RecurseObject -Object $prop.Value -ParentKey $currentKey } elseif ($prop.Value -is [string]) { # 仅处理字符串类型值,创建全局变量 Set-Variable -Name $currentKey -Value $prop.Value -Scope Global -Force } } } Invoke-RecurseObject -Object $InputObject # 导出JSON到指定路径(用于WSL配置) if ($ExportJsonPath) { $stringVars = Get-Variable -Scope Global | Where-Object { $_.Value -is [string] -and $_.Name -match '^\w+(\.\w+)*$' } | Select-Object Name, Value $stringVars | ConvertTo-Json | Out-File -FilePath $ExportJsonPath -Encoding utf8 } } }
关键逻辑说明
- 递归遍历:通过内部函数
Invoke-RecurseObject处理多级嵌套的PSCustomObject,拼接嵌套属性的键名(如Parent.Child格式) - 类型判断:仅当属性值为
[string]类型时,调用Set-Variable创建全局变量,指定-Scope Global确保变量在全局作用域生效 - JSON导出:通过可选参数
ExportJsonPath将生成的全局字符串变量导出为JSON,方便WSL读取配置
实现你的目标
1. 简化Set-Location导航
假设你的PSCustomObject是目录配置:
$dirConfig = [PSCustomObject]@{ Work = [PSCustomObject]@{ Project = 'C:\Projects\MyApp' Docs = 'C:\Projects\MyApp\Docs' } Personal = 'D:\Personal\Photos' } # 生成全局变量 ConvertTo-GlobalStringVariable -InputObject $dirConfig
之后直接用变量导航:
cd $Work.Project cd $Personal
2. 加入$PROFILE启动段
编辑你的PowerShell配置文件:
notepad $PROFILE
将以下内容添加到文件末尾(按需修改配置对象):
# 定义函数 function ConvertTo-GlobalStringVariable { # 粘贴上述完整函数代码 } # 目录配置对象 $dirConfig = [PSCustomObject]@{ Work = [PSCustomObject]@{ Project = 'C:\Projects\MyApp' Docs = 'C:\Projects\MyApp\Docs' } Personal = 'D:\Personal\Photos' } # 启动时自动生成全局变量并导出JSON到WSL可访问路径 ConvertTo-GlobalStringVariable -InputObject $dirConfig -ExportJsonPath '/mnt/c/Users/YourUser/dir-config.json'
保存后重启PowerShell,变量会自动加载。
3. WSL Bash配置读取JSON
在WSL的~/.bashrc中添加以下脚本(需安装jq):
# 读取Windows导出的JSON配置 DIR_CONFIG="/mnt/c/Users/YourUser/dir-config.json" if [ -f "$DIR_CONFIG" ]; then jq -r '.[] | "export \(.Name)=\(.Value)"' "$DIR_CONFIG" | while read -r line; do eval "$line" done fi
重启WSL终端后,即可使用同样的变量导航(如cd $Work.Project)。
4. 函数独立调用优化
当前函数已通过Param()块实现独立调用,支持管道输入:
# 管道输入方式 $dirConfig | ConvertTo-GlobalStringVariable -ExportJsonPath 'C:\temp\vars.json'
内容的提问来源于stack exchange,提问作者Richard Joubert
相关产品推荐
相关产品推荐

