2016-04-07 3 views
1

PowerShell実行可能ファイルのPHPスクリプトから返される配列値のリストがあります。これらの値は、Windows Server上のアクティブなプロジェクトに対応しています。私は自分のC:/ドライブに、そのサーバーによって処理された各プロジェクトのサブフォルダがあるprojectsフォルダを持っています。構造は次のようになります。Powershell - フォルダ内のサブフォルダを配列値に基づいて削除しないようにする

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

これまでのところ、4つのプロジェクトが処理されたことを示しています。

毎日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文字列が文字列のリストを返すと仮定しています。しかし、あなたの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 
    } 
    } 
} 

、その後、テストラインは、代わりに次のようになります。

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

'$のactive_projects'は、整数の配列リストです。しかし、 '[int] $ project'変換を実行すると、" "System.Int32"型のエラーに "System.IO.DirectoryInfo"型の "373"値を変換できません。 "変換を行わないと、アクティブなプロジェクトに関連するサブフォルダを含むすべてのサブフォルダがif条件に該当します。条件付きで 'Write-Hosts'を2回実行しました。値が正しいと思われます。 '-notcontains'はタイプが異なるので、私のアクティブなプロジェクトを捕まえられないのでしょうか? –

+0

いいえ、私はそれが '$ project.Name'でなければならないので間違っています!私は答えを修正しました。 –

関連する問題