PowerShell脚本-获取子项
我已经编写了一个脚本,用于从服务器归档日志文件。我的状态很好,除了递归性和不递归性 我似乎遇到的问题是,当Get ChildItem不是递归的并且PowerShell脚本-获取子项,powershell,get-childitem,Powershell,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-c
-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
苏欧???我有一个幻想,我所要做的就是分支到没有递归开关的脚本路径。(顺便问一下,是否可以可变地应用参数以避免重复的代码路径,其中唯一的变化是cmdlet的参数?)
无论如何,这是我的完整性脚本,除了我的GetChildItem问题
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 Help for Get 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.
-包括
仅检索指定的项。此参数的值限定路径参数。输入路径元素
ent或模式,如“*.txt”。允许使用通配符。
Include参数仅在命令包含Recurse参数或路径指向
e目录的内容,如C:\Windows\*,其中通配符指定C的内容:\
Windows目录。
答案在命令的完整描述中(get-help get-childitem-full):
Include参数是有效的
仅当命令包含
递归参数或路径指向
目录的内容,例如
C:\Windows\*,其中通配符
字符指定文件的内容
C:\Windows目录
因此,下面的代码将在没有递归的情况下工作
PS C:\foo> Get-childitem -path "c:\foo\*" -Include *.txt
这是意料之中的行为,但无可否认令人困惑。从Get ChildItem帮助文件:
-Include <string[]>
-包括
仅检索指定的项。此参数的值限定路径参数。输入路径元素或模式,例如“*.txt”。允许使用通配符
Include参数仅在命令包含Recurse参数或路径指向目录的内容时有效,例如C:\Windows*,其中通配符指定C:\Windows目录的内容
ps>帮助目录-完整|更多
希望这有帮助
-Oisin我只是在发布后通过单击Get ChildItem标签看到了这一点。像OP一样,过滤器是特定于提供者的,我已经在使用它做其他事情了。我想我只是这个问题的延续。这是一个记录在案的行为,我需要RTFM。我发誓我确实得到了帮助,但我掩盖了这一点。谢谢大家!基本上,Path和Recurse确定初始对象列表,然后通过Include和Exclude过滤这些对象。所以“C:\foo”将为您提供一个目录信息对象。“C:\foo*”将提供“foo”的所有内容。