【问题标题】:Powershell - Include subfolders in Get-ChildItemPowershell - 在 Get-ChildItem 中包含子文件夹
【发布时间】:2018-03-26 20:15:18
【问题描述】:

好的,还有一个 powershell 问题。

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

“主文件夹”->“X0”->“X00000”所以如果我有 X0897,需要查看主文件夹的子文件夹“X0”,以查找名为“X0”的子文件夹X0897"。

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

这是使用递归完成的吗?我在正确的道路上吗?我需要放弃 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!"
  }

}

【问题讨论】:

  • 子文件夹会一直是文件名的前两个字符吗?
  • 看起来第一个子文件夹总是文件名的前三个字符。因此,如果文件是“X123456”,则文件夹结构将是主文件夹 -> X12 -> X123456。我不知道这是否重要,但有时前三个会包括一个破折号。所以文件名可能是 X-1234,子文件夹会读取 X-1。在某些情况下,破折号可能位于末尾,即:X1-(如果文件名是 X1-123)
  • 等等,如果文件名以X0897开头那么需要复制到N:\Users\User\General\Test\X0\X0897吗?还是被复制到N:\Users\User\General\Test\X0\X00000\X0897
  • N:\Users\User\General\Test\X0\X0897

标签: powershell


【解决方案1】:

好的,我想我知道了:

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

【讨论】:

  • 没有骰子。我改变了它来代替 dFold = "$tDir$nFile" (我假设这是意图)。
  • 目的是 $targetFolder 将保存应复制文件的文件夹的路径。因此,对于以 X123456 $targetFolder 开头的文件将保存 C:\Users\User\General\Test\X12\X123456
  • 这是有道理的。本质上,$targetFolder 就像 $dFold,但它实际上是在指定子文件夹?编辑:我意识到我做错了什么。效果很好,谢谢!
猜你喜欢
  • 2019-08-27
  • 1970-01-01
  • 1970-01-01
  • 2019-08-26
  • 1970-01-01
  • 1970-01-01
  • 2015-10-29
  • 2020-09-08
  • 2013-11-19
相关资源
最近更新 更多