PowerShell脚本 - 获取 - ChildItem
-
21-09-2019 - |
题
我已经写了将用于归档日志文件从服务器的脚本。我在非常良好的状态与一切,但递归与否的 GET-ChildItem ...
我似乎有问题是,当GET-ChildItem不递归-Include
存在只有一个过滤器,它被忽略!或者,我做错了什么(可能)。
我已经清理了输出一点点...
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
的sooo ???我有一个幻想,所有我必须做的是分公司不具有递归开关脚本的路径。 (顺便说,是有可能可变地应用参数,以避免重复的代码路径,其中仅可变性参数以一个小命令?)
总之,这里是我的完整性脚本,除了我的问题以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-帮助获得-childitem -full):
在包含参数是有效 仅当该命令包含 Recurse参数或路径导致 一个目录的内容,如 C:\ WINDOWS \ *,其中通配符 字符指定的内容 在C:\ Windows目录
因此,以下将工作而不递归。
PS C:\foo> Get-childitem -path "c:\foo\*" -Include *.txt
其他提示
这是预期的行为,但不可否认混乱。从Get-ChildItem帮助文件:
-Include <string[]>
只检索指定的项目。这个参数的值资格Path参数。输入路径元素或模式,诸如“* .TXT”。允许使用通配符。
,只有当该命令包括Recurse参数或路径导致目录的内容,如C include参数是有效的:\视窗*,其中通配符指定C的内容:\ Windows目录。
PS>帮助目录-full |更
希望这有助于,
-Oisin
我无法告诉你确切的原因吧(但我会继续寻找),但该行为在获取帮助的获取,ChildItem记载:
-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.
不隶属于 StackOverflow