題 使用powershell創建一個日誌文件


如何使用powershell創建日誌文件?

我正在使用此代碼創建日誌文件。

#  Log file time stamp:
$LogTime = Get-Date -Format "MM-dd-yyyy_hh-mm-ss"
#  Log file name:
$LogFile = 'C:\PSLogs\'+"LOG_"+$LogTime+".log"

if(---)
{
    ----
    ----
   "done" | Out-File $LogFile -Append -Force
}
else
{
  "Unlucky!!" | Out-File $LogFile -Append -Force
}

但它給我一個錯誤

Out-File:找不到路徑的一部分


6
2018-06-19 09:08


起源


文件夾是否已存在?我只能通過將其指向不存在的文件夾來重現您的錯誤。 - TheUser1024
@TheUser1024:不..它應該是@ runtime創建的.. - Vysakh
然後在代碼中預先創建它。只需確保Out-File在運行時可以寫入該文件夾。 - TheUser1024
@TheUser1024:但是當它第二次運行時,我認為會發生一個異常。那我怎麼處理呢? - Vysakh
得到答案..主要觀點僅來自TheUser1024。從那時起,我建立了解決方案。謝謝TheUser1024 ...... - Vysakh


答案:


#  Log file time stamp:
$LogTime = Get-Date -Format "MM-dd-yyyy_hh-mm-ss"
[xml] $var = Get-Content D:\ScriptMgr\Sample.xml
$ser = read-host "Enter the centre:"

#  Log file name:
$path = "C:\Logs\"

if([IO.Directory]::Exists($path))
{
    #Do Nothing!!
}
else
{
    New-Item -ItemType directory -Path C:\PSLogs
}

$LogFile = 'C:\PSLogs\'+$ser+$LogTime+".html"
if (($sea=$var.detail.centre | where {$_.name -eq $ser}) -ne $null)
{
    Write-Host "center:" $sea.name
    Write-Host "Servername:" $sea.servername
    Write-Host "ip:" $sea.ip
    Write-Host "Username:" $sea.uname
    Write-Host "Password:" $sea.pwd
    Write-Host "Database:" $sea.dbname
    "$LogTime Found" | Out-File $LogFile -Append -Force
}
else
{
    write-host "not listed!!!"
    "$LogTime Not Found" | Out-File $LogFile -Append -Force
}

5
2018-06-20 09:12