PowerShellのスクリプト - は、Get-ChildItemコマンドレット
-
21-09-2019 - |
質問
私は、サーバーからログファイルをアーカイブするために使用されるスクリプトを書きました。私はの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;
}
}
}
}
解決
答えは(GET-ヘルプGET-ChildItemコマンドレット-full)コマンドの完全な説明である。
パラメータが有効である含めます コマンドが含まれる場合にのみ、 再帰パラメータまたはパスのリードに 以下のようなディレクトリの内容、 C:\ WINDOWS \ *、ワイルドカード キャラクターはの内容を指定します C:\ Windowsディレクトリ
。
以下は、再帰なしで動作しますので。
PS C:\foo> Get-childitem -path "c:\foo\*" -Include *.txt
他のヒント
これは正常な動作が、確かに混乱しています。 Get-ChildItemコマンドレットのヘルプファイルから:
-Include <string[]>
取得し指定された項目のみ。このパラメータの値は、Pathパラメータを修飾します。 「* .txt」などのパス要素またはパターンを入力します。ワイルドカードは許可されています。
\ Windowsの*、ワイルドカード文字はCの内容を指定します。:\ Windowsディレクトリコマンドは、再帰パラメータまたはCのようなディレクトリの内容へのパスリードを含んする場合にのみパラメータが有効である含めます。
PS>ヘルプDIR -full |より
ホープ、このことができます、
-Oisin
私はあなたを伝えることができない正確な理由のそれ(私は探し続けるだろう)が、行動がGET-ChildItemコマンドレットのためのGet-ヘルプに記載されます:
-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.