使用Powershell if/then根据文件夹中的文件数创建不同的退出代码



我正在尝试创建一个脚本,计数文件夹中的每个文件。计数部分本身的工作很好,但我希望使它输出一个基于计数的退出代码,以便在自动化工具中使用。

value | message  | exit code
=15   "finish OK" (0) 
<15   "not ready" (1)
>15   "corruption" (2)

我试了下面的,但它说';第2行字符14不能绑定参数'路径',因为它是空的">

$filecount = Write-Host ( Get-ChildItem -File "c:test" | Measure-Object ).Count
if(test-path $filecount){
if((get-item $filecount).Count = 15){
"Finish OK";EXIT 0
}
if((get-item $filecount).Count > 15){
"CORRUPTION";EXIT 2}
else{"REVIEW DATA"}

}
else{"NOT READY";EXIT 1}

按照我的评论。你可能把这个问题复杂化了。像下面这样的事情可能更谨慎。

$FileCount = (Get-ChildItem -File 'D:Temp' | Measure-Object).Count
switch ($FileCount)
{
{$FileCount -eq 15} {'finish OK' }
{$FileCount -lt 15} {'not ready'}
{$FileCount -gt 15} {'corruption'}
}
# Results
<#
corruption
#>

PowerShell变量压缩,将值赋给变量并同时输出到屏幕,就是这样。

($FileCount = (Get-ChildItem -File 'D:Temp' | Measure-Object).Count)
# Results
<#
100
#>

那么,在多个文件夹中这样做可以像这样:

Clear-Host
Get-ChildItem -Path 'D:TempCheckFileCount' | 
ForEach-Object {
$FolderName = $PSItem.Name
($FileCount = (Get-ChildItem -File $PSItem.FullName | Measure-Object).Count)
switch ($FileCount)
{
{$FileCount -eq 15} {"$FolderName : finish OK" }
{$FileCount -lt 15} {"$FolderName : not ready"}
{$FileCount -gt 15} {"$FolderName : corruption"}
}
}
# Results
<#
15
EqualTo15 : finish OK
16
GreaterThan15 : corruption
14
LessThan15 : not ready
#>

结果如下:与postanote的解非常相似

param([string]$arg1)
$filecount = Write-Output ( Get-ChildItem -File "$arg1" | Measure-Object 
).Count
if($filecount -eq 15) {
"Finish OK";EXIT 0
}
if($filecount -ge 15){
"CORRUPTION-Review Source";EXIT 2
}
else{"NOT READY, RUN DOWNLOAD AGAIN...";EXIT 1
}

最新更新