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

PowerShell日志功能需求:远程创建文件夹并记录操作日志

我来帮你完善这个带日志功能的PowerShell脚本,确保每台远程机器的操作细节都能被完整记录下来。下面是修改后的完整脚本,附带详细的功能说明:

完整脚本实现

# 定义通用日志写入函数
function Write-Log {
    param(
        [Parameter(Mandatory=$true)]
        [string]$Message,
        [string]$LogPath = ".\remote_operation_default.log"
    )
    # 生成带时间戳的日志条目
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] $Message"
    # 追加写入日志文件,不存在则自动创建
    Add-Content -Path $LogPath -Value $logEntry -Force
}

# 服务器列表存储路径
$serverListPath = ".\input.txt"
# 全局日志文件路径(也可改为按单台服务器生成独立日志)
$globalLogPath = ".\remote_folder_creation.log"

# 交互式输入服务器名称,空输入时停止
while ($serverInput = Read-Host "Enter remote server name (press Enter to finish input)") {
    if ([string]::IsNullOrWhiteSpace($serverInput)) { break }
    # 清理输入内容并追加到列表文件
    $serverInput.Trim() | Out-File $serverListPath -Append -Encoding utf8
}

# 读取服务器列表(过滤空行)
$targetServers = Get-Content -Path $serverListPath | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }

# 遍历服务器执行操作
foreach ($server in $targetServers) {
    $server = $server.Trim()
    Write-Log -Message "Initiating folder creation on server: $server" -LogPath $globalLogPath

    try {
        # 远程执行文件夹创建操作,捕获执行结果
        $remoteResult = Invoke-Command -ComputerName $server -ScriptBlock {
            $targetFolder = "C:\TestFolder"
            Write-Host "Processing folder creation at $targetFolder on $env:COMPUTERNAME"
            
            # 强制创建文件夹(已存在则不报错)
            $createdFolder = New-Item -Path $targetFolder -ItemType Directory -Force -ErrorAction Stop
            return "✅ Success: Folder created at $($createdFolder.FullName) on $env:COMPUTERNAME"
        } -ErrorAction Stop

        # 将远程成功结果写入日志并在控制台输出
        Write-Log -Message $remoteResult -LogPath $globalLogPath
        Write-Host $remoteResult -ForegroundColor Green
    }
    catch {
        # 捕获异常,记录错误日志并提示
        $errorDetail = "❌ Failed on server $server : $($_.Exception.Message)"
        Write-Log -Message $errorDetail -LogPath $globalLogPath
        Write-Host $errorDetail -ForegroundColor Red
    }
}

# 记录操作完成日志
Write-Log -Message "All remote folder creation operations completed" -LogPath $globalLogPath
Write-Host "Operation finished. Check detailed logs at: $globalLogPath"

关键修改说明

  • 新增Write-Log函数:自动给每条日志添加时间戳,支持自定义日志路径,确保操作记录可追溯。
  • 优化输入逻辑:添加了空输入终止判断,并用UTF-8编码保存服务器列表,避免乱码问题。
  • 完善错误处理:通过try/catch捕获远程连接、文件夹创建过程中的所有异常,错误信息会同时写入日志和控制台。
  • 双渠道反馈:远程操作的结果既会在控制台直观显示(带颜色区分成功/失败),也会完整写入日志文件。
  • 灵活日志存储:当前用全局日志文件记录所有服务器的操作,如果你需要给每台服务器单独生成日志,只需把$globalLogPath替换为".\log_$server.log"即可。

使用步骤

  1. 运行脚本后,逐个输入需要操作的远程服务器名称,输入完成后直接按回车结束输入。
  2. 脚本会自动读取服务器列表,远程连接每台机器并创建C:\TestFolder文件夹(已存在则跳过)。
  3. 所有操作细节(包括时间、服务器名、成功/失败信息)都会写入指定的日志文件,方便后续排查问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:36:13