【发布时间】:2016-05-19 00:11:56
【问题描述】:
我正在尝试编写以下脚本,该脚本会检查文件夹中的一组文件,如果它们存在,请将它们移动到“存档”文件夹。如果没有,请将错误消息写入屏幕和日志文件。
文件移动正常,因此 IF 的第一部分工作正常,但如果没有文件可移动,else 应该启动并输出错误....但事实并非如此。
variables.ps1:
#----- define parameters -----#
#----- Treat All Errors as Terminating -----#
$ErrorActionPreference = "Stop"
#----- Set count to 0 -----#
$count = 0
#----- get current date ----#
$Now = Get-Date
#----- define amount of days ----#
$Days = "0"
#----- define folder where files are located ----#
$SourceFolder = "C:\HG1\Test\Files"
#----- define folder where files are to be moved to ----#
$DestFolder = "C:\HG1\Test\Files\Archive"
#----- define folder where files are to be moved to ----#
$LogPath = "C:\HG1\archive.log"
#----- define extension ----#
$Extension = "*.log"
#----- define LastWriteTime parameter based on $Days ---#
$LastWrite = $Now.AddDays(-$Days)
#----- get files based on lastwrite filter and specified folder ---#
$Files = Get-Childitem $SourceFolder -Include $Extension -Recurse | Where {$_.LastWriteTime -le "$LastWrite"}
archive_files.ps1
#----- Call variables file variables.ps1 - MUST BE IN SAME LOCATION AS SCRIPT ----#
. ./variables.ps1
foreach ($File in $Files)
{
if ($File -ne $NULL)
{
move-item -path $File.FullName -destination $DestFolder
Add-Content $LogPath -value ("$((Get-Date).ToString('yyyy-MM-dd HH:mm:ss')) `t INFO: Archived File $File")
}
else
{
write-host "ERROR: No files to archive" -ForegroundColor "Red"
Add-Content $LogPath -value ("$((Get-Date).ToString('yyyy-MM-dd HH:mm:ss')) `t ERROR: No files to archive")
}
}
Add-Content $LogPath -value ("$((Get-Date).ToString('yyyy-MM-dd HH:mm:ss')) `t INFO: ***Archiving script completed successfully***")
任何帮助将不胜感激。
【问题讨论】:
-
$File永远不会为空,至少它将是一个字符串。您可以使用Test-Path检查现有文件,如本问题所示:stackoverflow.com/questions/1732250/… -
如果
$Files中没有文件,则简单地跳过foreach。else不应该与您的代码一起运行。 -
您是否要查看
$sourcefolder的所有子文件夹并根据.log 文件的存在对这些文件夹执行操作? -
不,我只是想在 C:\HG1\Test\Files 中查找任何 *.log 文件。如果存在任何 .log 文件,请将它们移动到 C:\HG1\Test\Files\Archive。如果不存在 .log 文件,则显示该错误。我认为 Test-Path 将成为答案,只需要尝试一下就可以让它工作。抱歉,在 PowerShell 方面,我是一个巨大的 N00b。
-
@dankellys - 我不认为
Test-Path是答案。您只是想看看$Files是否为空,无需为此测试路径。