powershell检查文件目录

时间:2014-02-12 17:29:33

标签: file validation powershell

我有一个应该包含10个文件的文件夹。每个文件名都不同(名称和扩展名),但是,它将包含一个模式。

例如

SomeThing.FILE0.DAT
SomeThing.FILE1.DAT
SomeThing.FILE2.DAT
 and so on till
SomeThing.FILE9.DAT

我的脚本目前没有任何检查。我手动运行它,确保所有文件都存在。

for ($i=0; $i -le 9; $i++)
{
    $FileString = "*FILE"+$i+"*"
    $MyFileName = Get-ChildItem e:\files -name -filter $($FileString)
}

但是,我需要自动化该过程,因此我想添加检查以确保:

a. Total of 10 files exist in that folder

$FC = ( Get-ChildItem c:\testing | Measure-Object ).Count;
if($FC -eq 10)
{
    echo "File Count is correct"
}
else
{
    echo "File Count is incorrect"
}

b. Each of the FILEX (X = 0-9) are present
c. Only one instance of each FILEX (X = 0-9) should be present. If multiple instances of FILEX are present, I need to display it on the screen saying that FILEX pattern is repeated multiple times.

如何进行剩余的检查?它看起来很简单,但更复杂......

2 个答案:

答案 0 :(得分:1)

$> if ((compare (ls -name | %{ ([regex]'(?<=.*FILE).*(?=.DAT)').match($_).groups[0].value } | Sort-Object) (0..9 | %{$_.ToString()}) -SyncWindow 0).Length -eq 0) { Write-Host "ok" }
ok

呃?

修改你的问题我们有类似“检查该目录只包含*FILEX.DAT个文件,其中X应该是0到9之间的每个可能的数字”。在powershell中它看起来应该是这样的:

$> if (allNumbersFromFileNames.IsEqualTo(0..9)) { Write-Info "ok" }

从当前目录中获取文件名中的所有数字:

$> ls -name | %{ ([regex]'(?<=.*FILE).*(?=.DAT)').match($_).groups[0].value }
0
1
2
3
5
6
7
8
9
4

我们使用([regex]'(?<=.*FILE).*(?=.DAT)')构建了正则表达式,并且当前目录中的每个文件名(ls -name | %{ $_ })都会解析其中的幻数并获得第一个匹配组的值。

最后,我们需要有这个string[]对象,对它进行排序并与数字字符串数组进行比较。 compare在这里很有用。

$> if ((compare 0..9 1..4).Length -eq 0) { Write-Host "equals" }
$> if ((compare 0..9 0..9).Length -eq 0) { Write-Host "equals" }
equals

把它们放在一起,你就得到了答案!

答案 1 :(得分:0)

由于正则表达式解决方案对我不起作用,我结束了你写一个粗略的逻辑。到目前为止它的作用。如果有更好的信息,请告知。

for ($i=0; $i -le 9; $i++)
{
$FileString = "*FILE"+$i+"*"

$ct = (Get-ChildItem "C:\testing" -name -filter $($FileString) | Measure-Object ).Count
if($ct -ne 1)
{
    if($ct -eq 0)
    {
        write-host "FILE"$i "is missing"
    }
    elseif ($ct -gt 1)
    {
        write-host $ct" instances of FILE"$i" found"
    }
    else
    {
        write-host "God help you."
    }
}
}
相关问题