4

サーバーからログ ファイルをアーカイブするために使用するスクリプトを作成しました。私はGet-ChildItemの再帰性かどうかを除いて、すべてにおいてかなり良い状態です ...

私が抱えていると思われる問題は、Get-ChildItem が再帰的で-Includeはなく、フィルターが 1 つしかない場合、無視されることです! または、私は何か間違ったことをしています(可能性があります)。

出力を少し整理しました...

PS C:\foo> Get-childitem -path "c:\foo"

Name
----
bar1.doc
bar2.doc
bar3.doc
foo1.txt
foo2.txt
foo3.txt

PS C:\foo> Get-childitem -path "c:\foo" -Include *.txt
PS C:\foo> Get-childitem -path "c:\foo" -Include *.txt -recurse

Name
----
foo1.txt
foo2.txt
foo3.txt

すっごく??? 再帰スイッチを持たないスクリプトのパスに分岐するだけでよいという幻想がありました。(ちなみに、唯一の可変性がコマンドレットへのパラメーターである重複したコード パスを回避するために、パラメーターを可変的に適用することは可能ですか?)

とにかく、Get-ChildItem に関する問題に加えて、完全を期すためのスクリプトを次に示します。

function MoveFiles()
{
    Get-ChildItem -Path $source -Recurse -Include $ext | where { $_.LastWriteTime -lt (Get-Date).AddDays(-$days) } | foreach {
        $SourceDirectory = $_.DirectoryName;
        $SourceFile = $_.FullName;
        $DestinationDirectory = $SourceDirectory -replace [regex]::Escape($source), $dest;
        $DestionationFile = $SourceFile -replace [regex]::Escape($source), $dest;

        if ($WhatIf){
            #Write-Host $SourceDirectory;
            #Write-Host $DestinationDirectory;
            Write-Host $SourceFile -NoNewline
            Write-Host " moved to " -NoNewline
            Write-Host $DestionationFile;
        }
        else{
            if ($DestinationDirectory)
            {
                if ( -not [System.IO.Directory]::Exists($DestinationDirectory)) {
                    [void](New-Item $DestinationDirectory -ItemType directory -Force);
                }
                Move-Item -Path $SourceFile -Destination $DestionationFile -Force;
            }
        }
    }
}
4

3 に答える 3

10

答えは、コマンドの完全な説明にあります (get-help get-childitem -full):

Include パラメーターは、コマンドに Recurse パラメーターが含まれている場合、またはパスが C:\Windows\* などのディレクトリの内容につながる場合にのみ有効です。ここで、ワイルドカード文字は C:\Windows ディレクトリの内容を指定します。

したがって、以下は再帰なしで機能します。

PS C:\foo> Get-childitem -path "c:\foo\*" -Include *.txt
于 2009-09-02T21:33:28.893 に答える
2

これは予想される動作ですが、紛らわしいことは確かです。Get-ChildItem ヘルプ ファイルから:

-Include <string[]>

指定されたアイテムのみを取得します。このパラメーターの値は、Path パラメーターを修飾します。「*.txt」などのパス要素またはパターンを入力します。ワイルドカードを使用できます。

Include パラメーターは、コマンドに Recurse パラメーターが含まれている場合、またはパスが C:\Windows* などのディレクトリの内容につながる場合にのみ有効です。ここで、ワイルドカード文字は C:\ Windows ディレクトリの内容を指定します。

ps> help dir -full | もっと

お役に立てれば、

-オイシン

于 2009-09-02T21:35:03.133 に答える
1

正確な理由はわかりませんが (引き続き調べます)、動作は Get-ChildItem の Get-Help に記載されています。

-Include <string[]>
    Retrieves only the specified items. The value of this parameter qualifies the Path parameter. Enter a path elem
    ent or pattern, such as "*.txt". Wildcards are permitted.

    The Include parameter is effective only when the command includes the Recurse parameter or the path leads to th
    e contents of a directory, such as C:\Windows\*, where the wildcard character specifies the contents of the C:\
    Windows directory.
于 2009-09-02T21:30:11.927 に答える