You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell脚本:网络可用性检查与文件日志功能优化求助

改进后的PowerShell脚本
Param(
    [Parameter(Mandatory=$true)]
    [string]$src,    
    [Parameter(Mandatory=$true)]
    [string]$trgt,
    [Parameter(Mandatory=$true)]
    [string]$log,
    [Parameter(Mandatory=$true)]
    [ValidateSet("copy", "move")]
    [string]$plot
)

# 自定义日志写入函数,生成结构化日志
function Write-OperationLog {
    param(
        [string]$Message,
        [string]$Level = "INFO"
    )
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] $Message"
    Add-Content -Path $log -Value $logEntry
    Write-Host $logEntry
}

try {
    # 启动控制台转录,补充记录所有操作细节
    Start-Transcript -Path $log -Append -IncludeInvocationHeader

    # 记录操作启动信息
    Write-OperationLog -Message "启动$plot操作:源路径=$src,目标路径=$trgt"

    # 验证源路径可用性
    if (-not (Test-Path -Path $src -ErrorAction Stop)) {
        throw "源路径无法访问:$src"
    }
    Write-OperationLog -Message "源路径验证通过:$src"

    # 验证目标路径/父路径可用性(处理目标为文件的场景)
    $targetBasePath = if ([string]::IsNullOrEmpty((Split-Path -Path $trgt -Parent))) { $trgt } else { (Split-Path -Path $trgt -Parent) }
    if (-not (Test-Path -Path $targetBasePath -ErrorAction Stop)) {
        throw "目标路径/父路径无法访问:$targetBasePath"
    }
    Write-OperationLog -Message "目标路径验证通过:$trgt"

    # 执行指定操作
    switch ($plot) {
        "copy" {
            Copy-Item -Path $src -Destination $trgt -Recurse -Force -ErrorAction Stop
            Write-OperationLog -Message "$plot操作执行完成" -Level "SUCCESS"
        }
        "move" {
            Move-Item -Path $src -Destination $trgt -Force -ErrorAction Stop
            Write-OperationLog -Message "$plot操作执行完成" -Level "SUCCESS"
        }
    }
}
catch {
    $errorDetail = "操作失败:$($_.Exception.Message)"
    Write-OperationLog -Message $errorDetail -Level "ERROR"
    throw $_ # 抛出错误,便于定时任务感知失败状态
}
finally {
    # 确保转录停止,避免日志文件锁定
    try {
        Stop-Transcript -ErrorAction SilentlyContinue
    }
    catch {}
}

核心改进说明

  • 参数合法性校验:

    • 所有参数设为必填,避免遗漏关键配置
    • 限制$plot只能传入copy或move,防止非法操作类型
  • 路径可用性检查:

    • 用Test-Path配合-ErrorAction Stop验证源路径存在性
    • 针对目标路径,优先验证其父路径(如果目标是文件),确保网络共享可访问
  • 结构化日志增强:

    • 自定义日志函数,统一记录时间戳、日志级别、操作关键信息
    • 日志采用追加模式,避免覆盖历史记录;同时保留Start-Transcript记录完整控制台输出
  • 全流程错误处理:

    • 用try/catch/finally包裹核心逻辑,捕获所有异常并写入日志
    • finally块强制停止转录,防止日志文件被长期锁定
    • 错误时重新抛出异常,方便定时任务(如Windows任务计划)识别失败
  • 操作鲁棒性提升:

    • 给Copy-Item和Move-Item添加-Force参数,支持覆盖已存在的目标文件/文件夹(可根据需求移除)
    • Move-Item可按需添加-Recurse参数,支持移动文件夹

内容的提问来源于stack exchange,提问作者Dnice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 23:41:11