我对脚本有以下要求:自定义日志文件创建 - Powershell
a。获取脚本名称和路径。 b。创建一个ScriptPath \ Log-Time | date \ Logfile.Log c。给用户3个选项,根据输入更新日志文件。
对于上述要求,香港专业教育学院创建了以下脚本:
#Variables Declaration-------------------------------------------
$pat = Split-Path $script:MyInvocation.MyCommand.Path -parent
$LogTime = Get-Date -Format "MM-dd-yyyy_hh-mm-ss"
$a = "[Info]:"+$LogTime+" Logged into Server"
$b = "[Warning]:"+$LogTime+" Unauthorized Access"
$c = "[Error]:"+$LogTime+" Wrong Credentials"
$ScriptName = $MyInvocation.MyCommand.Name
$path = $pat
#Folder and Log Creation------------------------------------------
if([IO.Directory]::Exists($path))
{
$m = New-Item -ItemType directory -Path $path -name Log
$n = New-Item -ItemType directory -Path $m -name $LogTime
}
$LogName = $ScriptName+"_Log_"+$LogTime+".log"
$log = New-Item -ItemType file -path $n -name $LogName
# Log Function------------------------------------------------------
log($in)
function log
{
$in = Read-Host "Enter your Option"
if ($in -eq "0")
{
$latest = Get-ChildItem -Path $n | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$p = $path+$latest.name
Add-Content $p -value $a
}
elseif ($in -eq "1")
{
$latest = Get-ChildItem -Path $n | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$p = $path+$latest.name
Add-Content $p -value $b
}
elseif ($in -eq "2")
{
$latest = Get-ChildItem -Path $n | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$p = $path+$latest.name
Add-Content $p -value $c
}
else
{
$o = "Invalid Input"
$o
}
Move-Item $p $n
}
每当我跑,我得到创建了两个日志文件。
Exec2.ps1_Log_04-04-2014_10-21-11.log & & & & MExec2.ps1_Log_04-04-2014_10-21-11.log [M是其中脚本运行的文件夹]
第一个日志文件是空的,而第二个日志文件包含文本。
任何人都可以请帮我解决这个问题吗?如果可能的话,使剧本简短而甜蜜?
感谢和问候, 凯因