Powershell删除6天的旧文件夹

时间:2014-05-26 17:17:51

标签: c# powershell automation teamcity

我必须制作PS脚本才能将其与我们的自动化软件集成。我是PS的初学者,我做了一些尝试,但仍然没有成功。这是我的任务。 我有一个参数将用作输入参数。这将是远程磁盘路径 %setupRootPath%。此目录有多个子目录,如(Beta,Testing,Release等),每个子目录都有项目名称。在连续集成系统中,每个项目都会获得Build Nomber,所以最后我得到了像

这样的东西
  • %setupRootPath%\贝塔\ ProjektA \ Build1000
  • %setupRootPath%\贝塔\ ProjektA \ Build1003
  • %setupRootPath%\贝塔\ ProjektA \ Build1004
  • %setupRootPath%\贝塔\ ProjektB \ Build1007
  • %setupRootPath%\贝塔\ ProjektB \ Build1008
  • %setupRootPath%\贝塔\ ProjektB \ Build1009
  • %setupRootPath%\贝塔\ ProjektB \ Build10010
  • %setupRootPath%\系统测试\ ProjektA \ Build1002

目前有数百个项目,我制作的C#代码可以满足我的需求,但如果我可以通过PS而不是C#来运行它,那将会非常棒#/ p>

所以这是C#Code

class Program
{
    const string rootDirPath = @"\\pcName\AutomationProcess\Deployment";
    const int keepNum = 1;
    const int deployDepth = 2;

    static void Main(string[] args)
    {
        var delDir = new DirectoryInfo(rootDirPath);
        var currentDateTime = DateTime.Now;

        int currentDetph = 0;
        var deployPathes = new Dictionary<DirectoryInfo, int>();
        GetDeployDirectories(delDir, currentDetph, deployPathes);

        foreach (var projektDir in deployPathes.Keys)
        {
            var dirInfoArray = projektDir.GetDirectories();
            if (dirInfoArray != null)
            {
                var sortedDeploymentDirs = from d in dirInfoArray
                                           where (currentDateTime - d.LastWriteTime).Days > 6
                                           orderby d.LastWriteTime
                                           select d;
                var deploymentDirsArray = sortedDeploymentDirs.ToArray();
                if (deploymentDirsArray.Length > keepNum)
                {
                    for (int i = 0; i < deploymentDirsArray.Length - keepNum; i++)
                    {
                        Console.WriteLine("Delete: {0}", deploymentDirsArray[i].FullName);
                    }
                }
            }
        }
    }

    private static void GetDeployDirectories(DirectoryInfo currentDirectory, int currentDetph, Dictionary<DirectoryInfo, int> resultDictionary)
    {
        currentDetph++;

        foreach (DirectoryInfo subDir in currentDirectory.GetDirectories())
        {
            if (currentDetph < deployDepth)
            {
                subDir.Refresh();
                GetDeployDirectories(subDir, currentDetph, resultDictionary);
            }
            else if (currentDetph == deployDepth)
            {
                resultDictionary.Add(subDir, currentDetph);
            }
        }
    }
}

我无法删除所有旧文件,我必须删除超过6天的所有文件,但即使它较旧,也要保留最后一个版本。

所以删除后我应该得到这样的结果

  • %setupRootPath%\ Beta \ ProjektA \ Build1000(已删除)
  • %setupRootPath%\ Beta \ ProjektA \ Build1003(已删除)
  • %setupRootPath%\ Beta \ ProjektA \ Build1004(如果删除则更旧,然后没有,跳过)
  • %setupRootPath%\ Beta \ ProjektB \ Build1007(已删除)
  • %setupRootPath%\ Beta \ ProjektB \ Build1008(已删除)
  • %setupRootPath%\ Beta \ ProjektB \ Build1009(不超过6天,已跳过)
  • %setupRootPath%\ Beta \ ProjektB \ Build10010(不超过6天,已跳过)
  • %setupRootPath%\ SystemTesting \ ProjektA \ Build1002(较旧但只有一个,跳过)

我会尝试一下tommorow。但是,如果有人会帮助。我会很满意:) 以下是我目前的状态。 它可以工作,但只有当我提供整个Projekt文件,而不仅仅是根目录时;(

param([String] $delpath=\\pcName\AutomationProcess\Deployment\Beta\ProjektA\",[String] $keepNum="1")
function Get-SubDirDate($directory)
{
    $datetime = $directory.LastWriteTime
    $SubDirDatealldir = gci $directory.FullName -filter * | ? { $_.PSisContainer -eq $true} 
    $SubDirDatealldir = @($SubDirDatealldir)
    foreach ($subdir in $SubDirDatealldir)
    {
        $subdir = $subdir -as [system.io.directoryinfo]

        if ($subdir)
        {
            $days = $subdir.LastWriteTime

            if ($days -ge $datetime)
            {
                $datetime = $days
            }
        }
    }
    $datetime
}

cd $delpath
$localdir = get-location
if ($localdir.Path.IndexOf($delpath) -ne -1)
{
    $datehash = @{}
    $CurrentTime = Get-Date

    # Mach es rekursive ;(

    $alldir = gci -filter * | ? { $_.PSisContainer -eq $true}
    $alldir = @($alldir)

    foreach ($dir in $alldir)
    {
        $dir = $dir -as [system.io.directoryinfo]
        $dir.Refresh()

        if (($dir) -and ($dir.Exists))
        {
            if (!$datehash.ContainsKey($dir.FullName))
            {
                $datehash[$dir.FullName] = Get-SubDirDate $dir
            }
        }
    }

    # Alle Verz. Aelter als 6 Tage bis auf die letzten n(=keepNum) loeschen 
    $itemCount = $datehash.Count

    if ($itemCount -gt ([int]$keepNum))
    {
        # Hash-Array nach Zeitstempel (=Value) absteigend sortieren 
        # (d.h. neuster Eintrag ist erstes Element) und die neusten n Faelle 
        # rausnehmen, damit diese nachfolgend nicht geloescht werden.             
        $datehashSorted = $datehash.GetEnumerator() | 
            Sort-Object Value -Descending | select-object -Last ($itemCount - [int]$keepNum)

        # Alle übrigen, die Älter als 6 Tage sind, löschen   
        $datehashSorted | foreach-object {

            $dir = $_.Name -as [system.io.directoryinfo] 
            $diffdays = ($CurrentTime-$_.Value).Days

            if ($diffdays -ge 6)
            {
               Write-Host ($dir.fullname)
               $dir.Delete($true) 
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我认为这就是你所追求的。从代码的角度来看,你当然可以提高效率,或者很容易将它转换为函数,但我试图让它变得可读。

# Your input parameter
$setupRootPath = "\\pcName\AutomationProcess\Deployment\"

# Retrieve the top level directories (Beta, Testing, Release, etc.).
Get-ChildItem $setupRootPath | Where-Object {$_.PSisContainer -eq $true} | ForEach-Object {
    $topDir = $_

# Pull the list of projects in the current top level dir.
    Get-ChildItem $topDir | Where-Object {$_.PSisContainer -eq $true} | ForEach-Object {
        $projectDir = $_

#Get the list of build folders, sorting by LastWriteTime, skipping the most recent, where the file is older than 6 days; and delete the remaining items.
        Get-ChildItem $projectDir | Where-Object {$_.PSisContainer -eq $true} | Sort-Object LastWriteTime -Descending | Select-Object -Skip 1 | Where-Object {((Get-Date)-$_.LastWriteTime).TotalDays -gt 6} | Remove-Item

    }
}