写两个Windows脚本,分别来对特定目录下的文件内容进行加密和解密并保存到指定位置
时间: 2024-03-20 18:39:43 浏览: 17
好的,以下是两个使用 PowerShell 编写的 Windows 脚本,分别用于对特定目录下的文件内容进行加密和解密并保存到指定位置:
加密脚本 encrypt.ps1:
```powershell
# 定义加密密钥
$key = "MySecretKey123"
# 指定需要加密的目录和保存加密文件的目录
$sourceDirectory = "C:\MyFiles"
$targetDirectory = "C:\MyEncryptedFiles"
# 创建保存加密文件的目录
New-Item -ItemType Directory -Path $targetDirectory -Force
# 获取指定目录下的所有文件
$files = Get-ChildItem -Path $sourceDirectory -File
# 对每个文件进行加密,并保存到指定目录
foreach ($file in $files)
{
$content = Get-Content $file.FullName
$encrypted = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($content))
$encrypted | ConvertTo-SecureString -Key $key | Out-File "$targetDirectory\$($file.Name).encrypted"
}
# 输出加密成功的信息
Write-Host "成功加密了" $files.Count "个文件。"
```
解密脚本 decrypt.ps1:
```powershell
# 定义加密密钥
$key = "MySecretKey123"
# 指定需要解密的目录和保存解密文件的目录
$sourceDirectory = "C:\MyEncryptedFiles"
$targetDirectory = "C:\MyDecryptedFiles"
# 创建保存解密文件的目录
New-Item -ItemType Directory -Path $targetDirectory -Force
# 获取指定目录下的所有加密文件
$files = Get-ChildItem -Path $sourceDirectory -File
# 对每个文件进行解密,并保存到指定目录
foreach ($file in $files)
{
$encrypted = Get-Content $file.FullName
$decrypted = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($encrypted))
$decrypted | Out-File "$targetDirectory\$($file.Name -replace '\.encrypted$','')"
}
# 输出解密成功的信息
Write-Host "成功解密了" $files.Count "个文件。"
```
请注意,这两个脚本也使用了一个自定义的密钥来进行加密和解密。在实际使用中,请根据需要修改密钥,确保安全性。同时,这两个脚本对指定目录下的文件进行加密和解密,并将结果保存到指定目录中,不会对源文件进行修改,如果需要对源文件进行修改,请自行修改脚本。