如果文件夹为空,则为Powershell命令

时间:2014-07-21 16:03:15

标签: powershell

我有一个脚本,我每天早上都会运行一些文件。它被移动的文件夹之一通常是空的,我试图找到一种方法让脚本在特定文件夹为空时跳过命令。这是脚本:

#Variable values
$date = (Get-Date).AddDays(-1)
$d = $date.Day
$m = $date.Month
$y = $date.Year
$basefolder = "S:\Servicing Director Archive\OutputFiles"
$archivefolder = "S:\Servicing Director Archive\OutputFiles\Archive"
$array = @("AssetMgr", "AssetMgr_LoanAdmin", "LoanAdmin", "Management", "Monthly     Analytics", "Weekly Analytics")
$childitem = 

#Create variable containing month number and name
if ($m -eq 1) { $month = "01_January" }
if ($m -eq 2) { $month = "02_February" }
if ($m -eq 3) { $month = "03_March" }
if ($m -eq 4) { $month = "04_April" }
if ($m -eq 5) { $month = "05_May" }
if ($m -eq 6) { $month = "06_June" }
if ($m -eq 7) { $month = "07_July" }
if ($m -eq 8) { $month = "08_August" }
if ($m -eq 9) { $month = "09_September" }
if ($m -eq 10) { $month = "10_October" }
if ($m -eq 11) { $month = "11_November" }
if ($m -eq 12) { $month = "12_December" }

#Loop to move files
Foreach ($folder in $array)
{

#Create yearly folder
New-Item -Path $archivefolder\$folder -Name $y -ItemType "directory" -Force
$yearlyfolder = "$archivefolder\$folder\$y"

#Create monthly folder
New-Item -Path $yearlyfolder -name $month -ItemType "directory" -Force
$monthlyfolder = "$yearlyfolder\$month"

#Create daily folder
New-Item -Path $monthlyfolder -Name "$m.$d.$y" -ItemType "directory" -Force
$dailyfolder = "$monthlyfolder\$m.$d.$y"

#Copy files to daily folder
Move-Item $basefolder\$folder\*.* $dailyfolder -Force
Move-Item $basefolder\$folder\letters\*.* $dailyfolder -Force


}

#Sends completion email
$body = "This is a notification that the files have been moved. Please confirm."
$sender = "support@statebridgecompany.com"
$recipient = "dpatino@statebridgecompany.com, slinnenkamp@statebridgecompany.com,     hlinnenkamp@statebridgecompany.com, mbernal@statebridgecompany.com"
$smtp = "sbd600"
$subject = "Event Manager Output Files"
Send-MailMessage -body $body -From $sender -To $recipient -SmtpServer $smtp -Subject     $subject

所以,我想要发生的是,如果$ basefolder \ $ array为空,请不要创建$ dailyfolder。我已经看过几个关于子项的线程,但我无法理解它们。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:0)

#Create daily folder
if((gci $basefolder\$folder -ErrorAction SilentlyContinue).count -ne 0) {
    New-Item -Path $monthlyfolder -Name "$m.$d.$y" -ItemType "directory" -Force
    $dailyfolder = "$monthlyfolder\$m.$d.$y"
}

修改
清洁版,使用Test-Path

if(test-path $basefolder\$folder\*) {
    New-Item -Path $monthlyfolder -Name "$m.$d.$y" -ItemType "directory" -Force
    $dailyfolder = "$monthlyfolder\$m.$d.$y"
}

答案 1 :(得分:0)

您可以使用Get-ChildItem的length属性来确定该文件夹中是否有项目,然后从那里继续。此外,创建文件夹会返回文件夹对象,因此您可以执行以下操作:

If((Get-ChildItem $basefolder\$folder).length -gt 0){
    $dailyfolder = New-Item -Path $monthlyfolder -Name "$m.$d.$y" -ItemType "directory" -Force
}