Get-ChildItem结果看起来像Powershell中的相对路径

Pau*_*ijs 4 powershell move

我想使用Powershell将文件夹(以及子文件夹甚至更深)扫描并从一个文件夹移动到另一个文件夹。

目前,我正在使用此命令管道。

Get-ChildItem  -recurse  -path sub\WORK  -filter "* OK" | Where-Object { $_.PSIsContainer } | foreach { Move-Item -path $_  -destination sub\OK }
Run Code Online (Sandbox Code Playgroud)

不幸的是,它不起作用,因为找到的结果是相对于的.\sub\WORK,尝试移动它们时,Move-Item抱怨这些文件夹不在当前文件夹中:

Move-Item : Cannot find path 'C:\TMP\2011-12-12 test 2 OK' because it does not exist.
Run Code Online (Sandbox Code Playgroud)

我希望$ _将包含:'C:\TMP\sub\WORK\2011-12-12 test 2 OK'因为这些是Powershell中的对象,而没有像Linux中的字符串。

ste*_*tej 5

如果您使用Get-ChildItem,请非常小心。最好的方法是将对象传送到,Move-Item而您无需再考虑它:

Get-ChildItem  -recurse  -path sub\WORK  -filter "* OK" | Where-Object { $_.PSIsContainer } | Move-Item -destination sub\OK
Run Code Online (Sandbox Code Playgroud)

(无需使用Foreach-Object

我要回答的主要原因是这一点:Get-ChildItem根据参数的不同构造对象。看例子:

PS C:\prgs\tools\Console2> gci -include * | % { "$_" } | select -fir 5
C:\prgs\tools\Console2\-verbose
C:\prgs\tools\Console2\1UpdateDataRepositoryServices.ps1
C:\prgs\tools\Console2\22-52-59.10o52l
C:\prgs\tools\Console2\2jvcelis.ps1
C:\prgs\tools\Console2\a
PS C:\prgs\tools\Console2> gci | % { "$_" } | select -fir 5
-verbose
1UpdateDataRepositoryServices.ps1
22-52-59.10o52l
2jvcelis.ps1
a
Run Code Online (Sandbox Code Playgroud)

然后,如果你使用$_的周期和PowerShell需要转换FileInfoGet-ChildItem字符串,它提供了不同的结果。当您用作的$_参数时发生了这种情况Move-Item。相当糟糕。

我认为存在一个报告此行为的错误。