Powershell实现自动备份Bitlocker到指定路径

文章目录

1.日志记录函数

function Write-Log {
    param (
        [string]$message
    )
    $logFile = "C:\temp\BitLockerKeyLog.txt"
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logMessage = "$timestamp - $message"
    Add-Content -Path $logFile -Value $logMessage
}

目的: 定义一个 Write-Log 函数,用于将信息写入日志文件。参数: $message 是要记录的日志信息。操作:

将当前时间和日期格式化。

将时间戳和日志信息合并成一条日志消息。

将日志消息追加到 C:\temp\BitLockerKeyLog.txt 文件中。

2.检查管理员权限

If (-Not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Log "脚本未以管理员权限运行,重新以管理员身份启动。"
    $arguments = "& '" + $myinvocation.mycommand.definition + "'"
    Start-Process powershell -Verb runAs -ArgumentList $arguments
    Exit
}

目的: 检查脚本是否以管理员权限运行。操作:

如果当前用户不是管理员,则记录日志并重新以管理员身份启动脚本。

使用 Start-Process 命令以管理员身份运行当前脚本,并退出当前进程。

3. 获取主机名

$Hostname = hostname
Write-Log "获取主机名:$Hostname"

目的: 获取当前计算机的主机名。操作:

使用 hostname 命令获取主机名。

记录获取到的主机名。

4. 获取BitLocker恢复密钥

try {
    $RecoveryKey = (Get-BitLockerVolume -MountPoint C).KeyProtector.recoverypassword
    Write-Log "成功获取BitLocker恢复密钥。"
} catch {
    Write-Log "无法获取BitLocker恢复密钥:$_"
    Exit
}

目的: 获取C盘的BitLocker恢复密钥。操作:

使用 Get-BitLockerVolume cmdlet 获取C盘的恢复密钥。

如果成功,记录日志。

如果失败,记录错误信息并退出脚本。

5. 检查并创建目标文件夹

$DestinationFolder = "C:\BitLocker Key"
If (-Not (Test-Path -Path $DestinationFolder)) {
    try {
        New-Item -ItemType Directory -Path $DestinationFolder
        Write-Log "目标文件夹不存在,已创建:$DestinationFolder"
    } catch {
        Write-Log "无法创建目标文件夹:$DestinationFolder,错误信息:$_"
        Exit
    }
}

目的: 确保目标文件夹存在。

操作:

检查目标路径是否存在。

如果不存在,则尝试创建该文件夹。

如果创建成功,记录日志。

如果创建失败,记录错误信息并退出脚本。

6. 将恢复密钥保存到文件

$FilePath = Join-Path -Path $DestinationFolder -ChildPath "$Hostname.txt"
try {
    $RecoveryKey | Out-File -FilePath $FilePath
    Write-Log "恢复密钥已成功保存到文件:$FilePath"
} catch {
    Write-Log "无法将恢复密钥保存到文件:$FilePath,错误信息:$_"
}

目的: 将获取到的BitLocker恢复密钥保存到指定文件中。操作:

构建目标文件的完整路径。

尝试将恢复密钥写入文件。

如果写入成功,记录日志。

如果写入失败,记录错误信息。

运行脚本可能会有组策略的问题,可以执行以下脚本解决:

Set-ExecutionPolicy RemoteSigned -Scope CurrentUser

完整代码:将以下代码存储为 .ps1 格式文件,为确保脚本能够运行成功,建议不要直接运行,可选择右键编辑使用Powershell ISE运行此脚本。

本脚本将强制使用管理员权限

# Set-ExecutionPolicy RemoteSigned -Scope CurrentUser   执行此命令前必须执行此命令

# 日志记录函数
function Write-Log {
    param (
        [string]$message
    )
    $logFileDir = "C:\temp"
    $logFile = Join-Path -Path $logFileDir -ChildPath "BitLockerKeyLog.txt"
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logMessage = "$timestamp - $message"

    # 检查并创建日志文件所在目录
    if (-not (Test-Path -Path $logFileDir -PathType Container)) {
        try {
            New-Item -Path $logFileDir -ItemType Directory -ErrorAction Stop | Out-Null
        } catch {
            Write-Host "无法创建日志文件目录:$logFileDir,错误信息:$_"
            Exit
        }
    }

    # 尝试写入日志
    try {
        Add-Content -Path $logFile -Value $logMessage -ErrorAction Stop
    } catch {
        Write-Host "无法写入日志文件:$logFile,错误信息:$_"
        Exit
    }
}

# 检查是否以管理员身份运行
If (-Not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Log "脚本未以管理员权限运行,重新以管理员身份启动。"
    # 如果没有管理员权限,则重新以管理员身份运行
    $arguments = "& '" + $myinvocation.mycommand.definition + "'"
    Start-Process powershell -Verb runAs -ArgumentList $arguments
    Exit
}

# 设置执行策略为 RemoteSigned(如果需要的话)
$currentExecutionPolicy = Get-ExecutionPolicy -Scope CurrentUser

# 如果当前策略不是 RemoteSigned,则修改为 RemoteSigned
if ($currentExecutionPolicy -ne 'RemoteSigned') {
    try {
        Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -Force
        Write-Log "已设置执行策略为 RemoteSigned -Scope CurrentUser。"
    } catch {
        Write-Log "无法设置执行策略为 RemoteSigned -Scope CurrentUser:$_"
        Exit
    }
}

# 获取主机名
$Hostname = hostname
Write-Log "获取主机名:$Hostname"

# 获取BitLocker恢复密钥
try {
    $RecoveryKey = (Get-BitLockerVolume -MountPoint C).KeyProtector.recoverypassword
    Write-Log "成功获取BitLocker恢复密钥。"
} catch {
    Write-Log "无法获取BitLocker恢复密钥:$_"
    Exit
}

# 检查目标文件夹是否存在,不存在则创建
$DestinationFolder = "C:\code" #更改存储路径地址
If (-Not (Test-Path -Path $DestinationFolder)) {
    try {
        New-Item -ItemType Directory -Path $DestinationFolder -ErrorAction Stop
        Write-Log "目标文件夹不存在,已创建:$DestinationFolder"
    } catch {
        Write-Log "无法创建目标文件夹:$DestinationFolder,错误信息:$_"
        Exit
    }
}

# 将恢复密钥保存到文件
$FilePath = Join-Path -Path $DestinationFolder -ChildPath "$Hostname.txt"
try {
    $RecoveryKey | Out-File -FilePath $FilePath -ErrorAction Stop
    Write-Log "恢复密钥已成功保存到文件:$FilePath"
} catch {
    Write-Log "无法将恢复密钥保存到文件:$FilePath,错误信息:$_"
}

# 如果需要,可以在此处将执行策略恢复为原始状态
# Set-ExecutionPolicy Default -Scope CurrentUser
温馨提示 : 非特殊注明,否则均为©李联华的博客网原创文章,本站文章未经授权禁止任何形式转载;IP地址:3.138.36.3,归属地:俄亥俄州Dublin ,欢迎您的访问!
文章链接:https://www.ooize.com/powershell-implementation-for-automatic-backup-of-bitlocker.html
订阅
提醒
guest

0 评论
内联反馈
查看所有评论
Popup Image

通知

本站原则上是免费提供技术支持,但是服务器维护和运营成本高,可以实行自由赞助:赞助

Loading...