Powershell - 在Get-ChildItem中包含子文件夹

时间:2018-03-26 20:15:18

标签: powershell

好的,还有一个PowerShell问题。

此脚本根据文件名的第一部分将文件移动到文件夹中。我现在遇到的问题是,他们最终被移动到的文件夹嵌套在顶层文件夹中,所以:

"主要文件夹" - > " X0" - > " X00000"因此,如果我有X0897,则需要查看主文件夹的子文件夹," X0",对于" X0"的子文件夹。名为" X0897"。

脚本必须能够查看"主文件夹",然后查看" X00000"的子文件夹。

这是用recurse完成的吗?我在正确的道路上吗?我是否需要删除GetChild?

# First, we retrieve a list of files where
# $sDir = Source Directory
$sDir = "N:\USERS\Username\General\Test1\"

# Generate a list of all files in source directory
$Files = (Get-ChildItem -recurse?? $sDir)

# $tDir = Root Target Directory (setting the directory the files are to be moved to)
$tDir = "N:\USERS\User\General\Test\"

# Loop through the list of file names
foreach($File in $Files)
{
# $wFile is set as the variable for our working file name
$wFile = $File.BaseName

# This command splits the working file name to extract the file number from the first part of the filename (nFile)
$nFile = $wFile.Split(' ')[0]


# dFold = the final destination folder of the file in the format of \\drive\folder\SubFolder\    
$dFold = "$tDir$nFile"

# Tests if the destination folder exists
if(Test-Path $dFold -PathType Container)
  {
  # If the folder exists then we move the file
  Copy-Item -Path $sDir$File -Destination $dFold

  # This denotes where the file has been moved to        
  Write-Host $File "Was Moved to:" $dFold
  Write-Host
  }
  # If a folder for the file number does not exist it will not be moved!
  else 
  {
  # This tells you if the file was not moved
  Write-Host $File "Was not moved!"
  }

}

1 个答案:

答案 0 :(得分:1)

好的,我想我拥有它:

$targetFolder = '{0}{1}\{2}' -f $tDir, $nFile.SubString(0,3), $nFile