如何用PowerShell脚本从分隔文本文件批量设置变量?
读取凭证文件并设置PowerShell变量的完整脚本
以下是完整的PowerShell脚本,可读取D:\SetCredentials.txt中的管道分隔凭证内容,并将各字段赋值给对应变量,供其他脚本调用:
# 读取凭证文件的原始内容 $credFileContent = Get-Content -Path "D:\SetCredentials.txt" -Raw # 按管道符(|)分割内容,过滤掉可能存在的空字符串 $credSegments = $credFileContent -split '\|' | Where-Object { $_ -notmatch '^\s*$' } # 校验分割后的字段数量是否符合要求 if ($credSegments.Count -ne 4) { Write-Error "凭证文件格式不正确,必须包含4个用|分隔的有效字段" exit 1 } # 将各字段赋值给具名变量,可根据实际需求修改变量名称 $targetServer = $credSegments[0] $accountId = $credSegments[1] $accountPassword = $credSegments[2] $accessToken = $credSegments[3] # (可选)调试输出变量值,确认赋值结果 Write-Host "目标服务器: $targetServer" Write-Host "账号ID: $accountId" Write-Host "账号密码: $accountPassword" Write-Host "访问令牌: $accessToken"
额外优化(若需安全存储密码)
如果后续脚本需要使用安全凭证对象,可将明文密码转换为安全字符串:
# 将明文密码转换为安全字符串 $securePassword = ConvertTo-SecureString $accountPassword -AsPlainText -Force # 创建PSCredential对象,用于身份验证场景 $psCredential = New-Object System.Management.Automation.PSCredential ($accountId, $securePassword)
内容的提问来源于stack exchange,提问作者Ben Martin2
相关产品推荐
相关产品推荐

