次のスクリプトを作成しようとしています。このスクリプトは、ファイルセットが存在する場合は、そのファイルを「アーカイブ」フォルダに移動します。そうでない場合は、画面とログファイルにエラーメッセージを書き込みます。foreach内で他のファイルが実行されていない
ファイルは正常に動作しているため、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***")
任意の助けいただければ幸いです。
'$ファイルの必要はありません "-ne $ nullがある" ので、$ NULL値のために入らない場合'がnullになることはありません。少なくとも文字列になります。この質問に示されているように、 'Test-Path'を使って既存のファイルをチェックすることができます:http://stackoverflow.com/questions/1732250/check-if-file-exist-and-run-a-batch-file-in -powershell –
'$ Files'にファイルがない場合、' foreach'は単純にスキップされます。 'else'は決してあなたのコードで実行されるべきではありません。 – Enigmativity
'$ sourcefolder'のすべてのサブフォルダを調べ、.logファイルの存在に基づいてそれらのフォルダに対してアクションを実行したいですか? – Matt