2016-07-11 7 views
1

問題は、-Excludeコマンドをこのスクリプトに挿入して、 '.pst'などのファイルの種類を指定しないようにすることです。 Where-Objectフィールドに$excludeを含める方法を今すぐ確認しました。Remove-Itemを呼び出す前に特定のファイルを除外する方法

$limit = (Get-Date).AddDays(2555) 
$path = "\\File Path" 
$log = "C:\Log output" 
$exclude = ".pst" 

# Delete files older than the $limit. <Use -WhatIf when you want to see what files/folders will be deleted before> 

Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt $limit} >$log 

Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } >> $log 

Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt $limit}| Remove-Item -Force -WhatIf 

Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force -WhatIf 

# Delete any empty directories left behind after deleting the old files. <Use -WhatIf when you want to see what files/folders will be deleted before> 

Get-ChildItem -Path $path -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } >> $log 

Get-ChildItem -Path $path -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse -WhatIf 

いずれのアイデアも大歓迎です。

+0

これは必要に応じて簡単に統合できます。どのPowerShellバージョンをお持ちですか?初心者には 'Tee-Object'を見てください。 – Matt

+0

'Where-Object'まで待つのはなぜですか? Get-ChildItemで '-Exclude'を使わないのはなぜでしょうか?最後の行は空のフォルダを削除していますか? – Matt

+0

PSVersion 4.0を使用しています。 – Josh

答えて

0

具体的な質問に答えるには、ファイル拡張子を調べる別の句をWhere-Objectに追加することができます。これは、1つの拡張子しか持たないために機能します。さらに追加したい場合は、演算子を変更する必要があります。

Get-ChildItem -Path $path -Recurse -Force | 
    Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt $limit -and $_.Extension -ne $exclude } > $log 

しかし、あなたのコードで見るべきより良いオプションがあります。 Where-Objectで後処理するのではなく、ほとんどの作業をWindowsファイルシステムに任せれば、時間と複雑さを節約できます。あなたは最初の数行を組み合わせることもできます。あなたはv4を持っているので、-File-Directoryスイッチを使って、それぞれのアイテムだけをプルすることができます。

Get-ChildItem -Path $path -Recurse -Force -File | 
    Where-Object {$_.LastWriteTime -lt $limit -and $_.CreationTime -lt $limit} | 
    Add-Content $log 

あなたの最初の数行が何をしているのか正確には分かりませんが、私はそれがあなたがすることを意味すると思います。 -Fileスイッチと結合日付句に注意してください。あなたはあなたもTee-Objectで、いくつかの繰り返しを削除することができます削除されたものをログに記録したい場合は

(未これに対処するための唯一の方法)

Get-ChildItem -Path $path -Recurse -Force -File | 
    Where-Object {$_.LastWriteTime -lt $limit -and $_.CreationTime -lt $limit} | 
    Tee-Object -FilePath $log | 
    Remove-Item -Force -WhatIf 

あなたがそれを必要な場所私は知りませんが、あなたにもできますただ-ExcludeGet-ChildItemを使用してpstファイルを省略してください。

Get-ChildItem -Path $_.FullName -Exclude $exclude -Recurse -Force 
+0

これは非常に役に立ちます。私は排他的なファイルタイプを手放すことのできる方法で使用する方法を検討していました。 – Josh

関連する問題