【发布时间】: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