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

如何阻止PowerShell脚本将新日志内容追加至旧日志文件?

解决PowerShell日志重复追加问题

你的脚本出现日志内容追加到旧文件的问题,核心原因有两点:一是Start-Transcript默认会向已存在的文件追加内容(即便用了时间戳,若脚本在同一秒内重复运行,会生成同名文件);二是脚本未调用Stop-Transcript结束转录会话,可能导致后续输出意外写入旧日志文件。

解决方案

  • 添加毫秒级时间戳:确保日志文件名绝对唯一,避免同一秒内运行时文件名重复
  • 调用Stop-Transcript:在脚本末尾结束转录,保证日志文件被正确关闭
  • 使用-Force参数:强制覆盖已存在的同名文件,彻底避免追加行为

修改后的完整脚本

Import-Module ActiveDirectory 

$inactiveDays = 40
$disableDaysInactive = (Get-Date).AddDays(-$inactiveDays)
# 加入毫秒级时间戳,确保文件名唯一
$todaysDate = (Get-Date -format "yyyyMMdd_HH-mm-ss-fff")

$LogFile = "C:\temp\Test\Disabled_and_Moved_User_Accounts_$todaysDate.log"
$DisabledOU = 'OU=Test Disable,OU=User Accounts,OU=Car,DC=car,DC=com'
$path = "OU=Test,OU=User Accounts,OU=Car,DC=car,DC=com"

$userlist = Get-ADUser -SearchBase $path -Filter { Enabled -eq $True } -Properties * | 
            Where-Object { 
                $_.description -notlike "*Service Account*" -and 
                $_.lastLogonDate -lt $disableDaysInactive -and 
                $_.lastLogonDate -ne $null 
            }

# 用-Force参数强制覆盖同名文件,避免追加
Start-Transcript -Path $LogFile -Force

if ($userlist) {    
    foreach ($user in $userlist) {        
        $desc = "Disabled on $(Get-Date) - Inactive for 40 Days $($user.Description)"         

        try {            
            Set-ADUser -Identity $user -Description $desc -Enabled $false            
            Move-ADObject -Identity $user -TargetPath $DisabledOU 
            Write-Output $user.DisplayName
        }        
        catch {            
            "Error occurred updating account {0}. {1}" -f $user.SamAccountName, $_        
        }    
    }
}
else {    
    "The existing users in 'User Accounts' are active within last 40 days"
}

# 结束转录会话,确保日志文件正确关闭
Stop-Transcript

额外说明

  • 毫秒级时间戳(-fff)保证了即使脚本在同一秒内多次运行,也会生成不同的日志文件名
  • Stop-Transcript会终止当前转录会话,避免后续操作意外写入已生成的日志文件
  • -Force参数确保如果日志文件意外存在(如手动创建),脚本会直接覆盖而非追加内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 07:24:56