如何通过PowerShell将用户输入传入JSON并生成用户名命名的JSON文件
解决方案
直接先获取用户输入,再动态填充哈希表的对应字段,就能解决参数传递的问题。完整脚本如下:
# 1. 获取用户输入 $inputUsername = Read-Host "请输入用户名" $inputIpAddress = Read-Host "请输入IP地址" $inputPassword = Read-Host "请输入密码" # 如果需要隐藏输入,改用 Read-Host "请输入密码" -AsSecureString 再转成明文 # 2. 构建带动态参数的哈希表 $body = @{ devices = @( @{ credentials = @( @{ label = 'username' value = $inputUsername sensitive = 'false' }, @{ label = 'Password' value = $inputPassword sensitive = 'true' } ) services = @( @{ name = 'RDP' url = "https://$inputIpAddress/?pauth=[proxy_token]&data=[connection:$inputUsername]" instructor = 'false' }, @{ name = 'HTTPS' url = "https://$inputIpAddress/?pauth=[proxy_token]&data=[connection:$inputUsername]" instructor = 'false' }, @{ name = 'SSH' url = "https://$inputIpAddress/?pauth=[proxy_token]&data=[connection:$inputUsername]" instructor = 'false' } ) connections = @( @{ id = "$inputUsername-rdp" protocol = 'rdp' hostname = $inputIpAddress port ='3389' } ) Parameters = @( @{ name = 'username' value = $inputUsername }, @{ name = 'password' value = $inputPassword } ) } ) } # 3. 转换为JSON并保存 $body | ConvertTo-Json -Depth 4 | Out-File "$inputUsername.json" -Encoding UTF8
关键说明:
- 先通过
Read-Host获取输入并赋值给变量,再把这些变量直接嵌入哈希表的对应位置,避免后续替换的麻烦 - 注意
connections里的id字段需要拼接用户名,用双引号包裹字符串才能解析变量 - 保存文件时直接用用户名作为文件名,确保每次生成的文件对应当前输入的用户
- 如果需要安全处理密码,用
-AsSecureString获取加密输入,再通过[System.Net.NetworkCredential]转换为明文填入哈希表
如果你坚持要先定义固定结构的哈希表再替换,也可以这么做:
# 先获取输入 $inputUsername = Read-Host "请输入用户名" $inputIpAddress = Read-Host "请输入IP地址" $inputPassword = Read-Host "请输入密码" # 定义基础哈希表 $body = @{ devices = @( @{ credentials = @( @{ label = 'username' value = 'myname' sensitive = 'false' }, @{ label = 'Password' value = 'Password@!' sensitive = 'true' } ) services = @( @{ name = 'RDP' url = "https://$inputIpAddress/?pauth=[proxy_token]&data=[connection:$inputUsername]" instructor = 'false' }, @{ name = 'HTTPS' url = "https://$inputIpAddress/?pauth=[proxy_token]&data=[connection:$inputUsername]" instructor = 'false' }, @{ name = 'SSH' url = "https://$inputIpAddress/?pauth=[proxy_token]&data=[connection:$inputUsername]" instructor = 'false' } ) connections = @( @{ id = 'myname-rdp' protocol = 'rdp' hostname = "192.168.1.6" port ='3389' } ) Parameters = @( @{ name = 'username' value = 'myname' }, @{ name = 'password' value = 'Password@!' } ) } ) } # 逐个替换字段 $body.devices[0].credentials[0].value = $inputUsername $body.devices[0].credentials[1].value = $inputPassword $body.devices[0].connections[0].hostname = $inputIpAddress $body.devices[0].connections[0].id = "$inputUsername-rdp" $body.devices[0].Parameters[0].value = $inputUsername $body.devices[0].Parameters[1].value = $inputPassword # 生成并保存JSON $body | ConvertTo-Json -Depth 4 | Out-File "$inputUsername.json" -Encoding UTF8
这种方式适合需要保留基础模板结构的场景,通过索引定位到哈希表的嵌套节点进行值替换。
内容的提问来源于stack exchange,提问作者karhtik
相关产品推荐
相关产品推荐

