【发布时间】:2020-07-09 15:25:42
【问题描述】:
我有以下函数write-log,我想把运行脚本时生成的日志放在一个子文件夹中,并将它们重命名为file.logs.old。此外,我想将最后的日志保留在脚本文件夹中。示例
最后的日志:
C:\scripts\powershellscript\logs.log
子文件夹旧日志:
C:\scripts\powershellscript\logfolder\
旧日志:
C:\scripts\powershellscript\logfolder\logs1.log.old
C:\scripts\powershellscript\logfolder\logs2.log.old
C:\scripts\powershellscript\logfolder\logs3.log.old
Etc...
我有以下功能,但它只保存最后一个日志并覆盖它:
function write-Log
{
Param (
[Parameter(Mandatory = $false)]
#Message
$Message,
[Parameter(Mandatory = $false)]
#Errormessage
$ErrorMessage,
[Parameter(Mandatory = $false)]
#Component that create the error
$Component,
[Parameter(Mandatory = $false)]
#Error Type
[int]$Type,
[Parameter(Mandatory = $true)]
#Filepath to the Logfile
$LogFile
)
#Create a Timestamp
$Date = Get-Date -Format "MM/dd/yyyy"
$time = Get-Date -Format "HH:mm:ss.fff"
#If you type a error message the type will automatically switch to type 3 Error
if ($null -ne $ErrorMessage)
{ $Type = 3
}
#If you type no Component the Component will set to space
if ($null -eq $Component)
{ $Component = " "
}
#If you set the type variable it is set to 1 automatically
if ($null -eq $Type)
{ $Type = 1
}
#create the log entry
$LogMessage = "<![LOG[$Message $ErrorMessage ]LOG]!>" + "<time=`"$time`" date=`"$Date`" component=`"$Component`" context=`"`" type=`"$Type`" thread=`"`" file=`"`">"
#write the log entry
$LogMessage | Out-File -Append -Encoding UTF8 -FilePath $LogFile
}
这是存储日志的当前变量
#Variable
$Logfile = "C:\Scripts\powershellscript\logs.log" #logfile path
我怎样才能做到这一点?我正在寻找需要添加到用户查询中的此功能的帮助。该脚本正在运行,但仅附加最后一个日志。并且长期检查旧日志是无法管理的。
谢谢
【问题讨论】:
-
[1] 编写和测试代码来做你想做的事。 [2] 将其转换为函数。 [3] 将该函数添加到脚本的开头。 [4] 在
Write-Log函数中的 OR 之前调用它来处理该过程。 -
嗨@Lee_Dailey,谢谢你的回答。我已经有了一个工作脚本,但它只保留和保存一个日志文件。我正在寻找的是在函数中自动创建日志,以便我将最后一个日志文件保存在脚本文件夹中,并将旧日志文件移动到子文件夹中进行归档。有什么方法可以进一步扩展我在帖子中为此范围添加的功能?据了解,您提到的 1、2、3、4 的所有步骤都有效,但只保存一个日志文件。
-
i 指的是要添加到您提供的代码中的 additional 函数。 [grin] 我会 [A] 在写入之前检查现有文件的大小或日期。 [B] 如果文件太大/太旧,则使用时间戳重命名文件。 ///// 另一种解决方案是每天创建一个新文件。像 - '是今天的文件吗?用它!如果不是从今天开始,请用今天的日期制作新的`-似乎涵盖了这个想法......而且它既简单又相当强大。
-
@Lee_Dailey,感谢您对此的意见。我发布了一些对我来说现在很好用的东西。问候,StackLad
-
我也是这么想的!很高兴看到你让它根据需要为你工作! [咧嘴]
标签: function powershell logging parameters