2016-04-07 48 views
1

我有我的PowerShell可執行文件中的PHP腳本返回的數組值的列表。這些值對應於我的Windows Server上的活動項目。我在我的C:/驅動器中有一個項目文件夾,該文件夾對於該服務器已處理的每個項目都有一個子文件夾。結構看起來像這樣:Powershell - 根據數組值刪除文件夾中的子文件夾

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

上面的信號表明服務器已經處理了四個項目到目前爲止。

我運行一個Scheduled Task 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聲明?

回答

2

您應該使用-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)) { 
+0

'$ active_projects'是一個整數數組列表。但是,如果我做'[int] $ project'轉換,我得到''不能轉換類型System.IO.DirectoryInfo的「373」值來鍵入「System.Int32」'錯誤。如果不進行轉換,則所有子文件夾(包括與活動項目相關的子文件夾)均屬於if條件範圍內。我在條件附近做了一些'Write-Hosts',看起來這些值是正確的。 「不包含」不能捕捉我活躍的項目,因爲它們是不同類型的? –

+0

不,我弄錯了,因爲它應該是'$ project.Name'!我已經修改了答案。 –

相關問題