创建windows脚本,设定时任务
实现功能:将某json文件中的某些值改成自己需要的值,并做定时任务,两个脚本来回切换,实现自动切换某功能(如限制升级、限制运行等)。将原有的UTF-8制作成相同格式不带BOM签名的。不然会有问题。并生成日志,只保留三天,自动删除多余的。
直接上脚本:
$file1 = "D:\pc\ftp\xxxxxxxx\xxxxxxx.json"
$file2 = "D:\pc\ftp\xxxxx\xxxxxx.json"
$files = @($file1, $file2)
$logDirectory = "D:\pc\ftp\xxxxxxx\log" # 日志文件所在的目录(需要自行创建log文件夹,否则会报错,无法写入)
$logFileName = "xxxxxx_" + (Get-Date -Format "yyyy-MM-dd") + ".txt" # 包含日期的日志文件名
# 定义一个函数来清理旧的日志文件,只保留最近三天的日志
function Cleanup-OldLogs($logDir, $daysToKeep) {
$cutoffDate = (Get-Date).AddDays(-$daysToKeep)
Get-ChildItem -Path $logDir -File |
Where-Object { $_.LastWriteTime -lt $cutoffDate } |
Remove-Item -Force
}
# 清理旧日志文件,只保留最近三天的
Cleanup-OldLogs -logDir $logDirectory -daysToKeep 3
foreach ($file in $files) {
$originalContent = $null
$newContent = $null
$logMessage = ""
$success = $false
if (Test-Path $file) {
try {
# 读取文件内容,使用UTF-8无BOM编码
$originalContent = [System.IO.File]::ReadAllText($file, [System.Text.Encoding]::UTF8)
# 替换内容(将AutomaticUpgrade中的值替换)
$newContent = $originalContent -replace '"AutomaticUpgrade": "no"', '"AutomaticUpgrade": "yes"'
# 如果内容没有变化,则不进行写入操作
if ($originalContent -ne $newContent) {
# 创建一个不带 BOM 的 UTF-8 Encoding 对象
$utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $false
# 写回文件,使用上面创建的不带 BOM 的 UTF-8 Encoding
[System.IO.File]::WriteAllText($file, $newContent, $utf8NoBomEncoding)
$success = $true
}
} catch {
$logMessage = "Failed to modify file: $file. Error: $_"
$success = $false
}
} else {
$logMessage = "File not found: $file"
$success = $false
}
# 获取当前时间戳
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
# 构建日志消息
if ($success) {
$logMessage = "$timestamp - Successfully modified file: $file"
} else {
$logMessage = "$timestamp - $logMessage"
}
# 只有当有变化或失败时,输出日志消息并追加到日志文件
if ($originalContent -ne $newContent -or -not $success) {
Write-Host $logMessage
$logMessage | Out-File -Append -FilePath (Join-Path $logDirectory $logFileName)
}
}
# 获取当前时间戳
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
# 写入完成日志,无论是否修改,都记录完成日志
$logMessage = "$timestamp - Modification process completed."
Write-Host $logMessage
$logMessage | Out-File -Append -FilePath (Join-Path $logDirectory $logFileName)
脚本自行获取并改变XXX中的路径及命名。
设置定时任务:运行tasksch.msc
另外定时任务有个默认三天自动删除计划任务,我就进了这坑了,辛苦配置的全被删了,幸亏之前有截图记录。各位注意避坑。
添加任务:

powershell -ExecutionPolicy Bypass -File D:\脚本路径\脚本名.ps1
其他有问题欢迎随时沟通。
**
还有个坑的地方,每次我的脚本设置定时任务后,过几天发现定时任务莫名奇妙的被删了,循环往复有三次。开始以为是人为,后来经过百度查阅各类文档,怀疑是360给删的任务,关键是360还没有输出任务,也查无痕迹,然后我就把360卸载了,我还特意把四个任务导出来放桌面。果然,到现在任务都没被删。360这个软件真是太过分了。。。
**

3118

被折叠的 条评论
为什么被折叠?



