【问题标题】:Powershell - Exclude Sub-Folders In Folder From Being Deleted Based on Array ValuesPowershell - 根据数组值排除文件夹中的子文件夹被删除
【发布时间】:2016-04-08 03:55:17
【问题描述】:

我的 PowerShell 可执行文件中有一个从 PHP 脚本返回的数组值列表。这些值对应于我的 Windows Server 上的活动项目。我的C:/ 驱动器中有一个项目文件夹,其中包含该服务器已处理的每个项目的子文件夹。结构看起来像这样:

/project-files
    /1
    /2
    /3
    /4

以上信号表明服务器到目前为止已经处理了四个项目。

我每天运行一个计划任务 Powershell 脚本来清理 project-files 文件夹。当我运行我的脚本时,我只想删除与当前未在服务器上运行的项目相对应的子文件夹。

我有以下 Powershell:

$active_projects = php c:/path/to/php/script/active_projects.php
if($active_projects -ne "No active projects"){
    # Convert the returned value from JSON to an Powershell array
    $active_projects = $active_projects | ConvertFrom-Json
    # Delete sub folders from projects folder
    Get-ChildItem -Path "c:\project-files\ -Recurse -Force |
    Select -ExpandProperty FullName |
    Where {$_ -notlike 'C:\project-files\every value in $active_projects*'}
    Remove-Item -Force
}

如果子文件夹编号对应于 $active_projects 数组中的项目编号,我想排除删除 project-files 文件夹中的子文件夹。

我将如何在此处编写Where 声明?

【问题讨论】:

    标签: powershell powershell-4.0


    【解决方案1】:

    您应该使用-notcontains 运算符来查看每个项目是否被列为活动项目。在下文中,我假设您的 PHP 脚本中的 JSON 字符串返回一个字符串列表。

    $active_projects = php c:/path/to/php/script/active_projects.php
    
    if ($active_projects -ne "No active projects") {
    
      # Convert the returned value from JSON to a PowerShell array
      $active_projects = $active_projects | ConvertFrom-Json
    
      # Go through each project folder
      foreach ($project in Get-ChildItem C:\project-files) {
    
        # Test if the current project isn't in the list of active projects
        if ($active_projects -notcontains $project) {
    
          # Remove the project since it wasn't listed as an active project
          Remove-Item -Recurse -Force $project
        }  
      }
    }
    

    如果你的 JSON 数组是一个整数列表,那么测试行应该是:

        if ($active_projects -notcontains ([int] $project.Name)) {
    

    【讨论】:

    • $active_projects 是一个整数数组列表。但是,如果我进行 [int] $project 转换,我会收到 "Cannot convert the "373" value of type System.IO.DirectoryInfo" to type "System.Int32" 错误。如果不进行转换,则所有子文件夹(包括与活动项目相关的子文件夹)都属于 if 条件。我围绕条件做了几个Write-Hosts,看起来值是正确的。 -notcontains 会不会因为它们的类型不同而无法捕捉到我的活跃项目?
    • 不,我弄错了,应该是$project.Name!我已经修改了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-28
    相关资源
    最近更新 更多