Powershell - 根据数组值排除文件夹中的子文件夹被删除

Powershell - Exclude Sub-Folders In Folder From Being Deleted Based on Array Values

我的 PowerShell 可执行文件中有一个从 PHP 脚本返回的数组值列表。这些值对应于我的 Windows 服务器上的活动项目。我的 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
}

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

我将如何在此处编写 Where 语句?

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

$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)) {