PowerShell中Get-Content如何无需固定路径读取password.txt与aes.key
解决方案
以下提供3种不同适用场景的实现方案,可根据实际分发需求选择:
方案1:读取脚本同级目录文件(最推荐,适合批量分发场景)
将脚本、password文件夹(内含password.txt和aes.key)统一打包分发,用户解压到任意路径都可直接运行,不需要修改任何配置:
# 自动获取当前脚本所在目录路径,PowerShell 3.0及以上版本原生支持 $scriptRoot = $PSScriptRoot # 拼接目标文件路径 $passwordPath = Join-Path -Path $scriptRoot -ChildPath "password\password.txt" $keyPath = Join-Path -Path $scriptRoot -ChildPath "password\aes.key" # 校验文件是否存在 if (-not (Test-Path -Path $passwordPath -PathType Leaf)) { Write-Error "未找到密码文件:$passwordPath" exit 1 } if (-not (Test-Path -Path $keyPath -PathType Leaf)) { Write-Error "未找到密钥文件:$keyPath" exit 1 } $serviceActPw = Get-Content -Path $passwordPath | ConvertTo-SecureString -Key (Get-Content -Path $keyPath)
方案2:自动全盘搜索匹配文件
如果文件存放位置完全不固定,可让脚本自动搜索系统盘的目标文件,取第一个匹配结果使用:
# 递归搜索C盘下的目标文件,忽略无权限访问的路径报错 $passwordPath = Get-ChildItem -Path C:\ -Filter "password.txt" -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty FullName $keyPath = Get-ChildItem -Path C:\ -Filter "aes.key" -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty FullName if (-not $passwordPath -or -not $keyPath) { Write-Error "系统中未找到所需的password.txt或aes.key文件,请检查文件是否存在" exit 1 } $serviceActPw = Get-Content -Path $passwordPath | ConvertTo-SecureString -Key (Get-Content -Path $keyPath)
注意:该方案首次运行时需要遍历系统盘,耗时较长;如果系统中存在多份同名文件,可能匹配到错误的文件,仅建议测试场景使用。
方案3:支持运行时手动指定路径
给脚本增加参数选项,既默认读取同级目录文件,也支持用户运行时自定义传入文件路径,灵活度最高:
# 定义脚本参数,不传值时默认读取同级目录下的对应文件 param( [Parameter(Mandatory = $false)] [string]$PasswordPath = (Join-Path -Path $PSScriptRoot -ChildPath "password\password.txt"), [Parameter(Mandatory = $false)] [string]$KeyPath = (Join-Path -Path $PSScriptRoot -ChildPath "password\aes.key") ) if (-not (Test-Path -Path $PasswordPath -PathType Leaf)) { Write-Error "密码文件路径不存在:$PasswordPath" exit 1 } if (-not (Test-Path -Path $KeyPath -PathType Leaf)) { Write-Error "密钥文件路径不存在:$KeyPath" exit 1 } $serviceActPw = Get-Content -Path $PasswordPath | ConvertTo-SecureString -Key (Get-Content -Path $KeyPath)
需要自定义路径时,运行脚本时传入对应参数即可:
.\你的脚本名称.ps1 -PasswordPath "D:\自定义路径\password.txt" -KeyPath "D:\自定义路径\aes.key"
内容的提问来源于stack exchange,提问作者Kim
相关产品推荐
相关产品推荐

