脚本结束后删除文件夹

时间:2019-11-19 10:42:02

标签: windows powershell

我目前正在编写一个脚本,该脚本接受一个文件文件夹,将第一个文件移至具有特定名称的文件夹,然后将其余文件移至具有名称数字的另一个文件夹。

我的脚本可以工作,但是它也可以移动文件夹并对其重命名。代码的哪一部分导致了此?

$path = "C:\Users\User1\Desktop\MergeTest\_First\"

$FileCount = Get-ChildItem -Path $path -File | Measure-Object | %{$_.Count}
$FirstFile = Get-ChildItem -Path $path -Force -File | Select-Object -First 1

$FinalReport = "C:\Users\User1\Desktop\MergeTest\___Final\TestOutput.xlsx"

Move-Item "C:\Users\User1\Desktop\MergeTest\_First\$FirstFile" $FinalReport

$Counter = 0;



Write-host $FileCount





for($Counter = 0; $Counter -lt $FileCount; $Counter++)
{


$FileInWork = Get-ChildItem -Path $path -Force -File | Select-Object -First 1

move-item "C:\Users\User1\Desktop\MergeTest\_First\$FileInWork" "C:\Users\User1\Desktop\MergeTest\__Second\$Counter.xlsx"
Write-host "File Moved"

}

2 个答案:

答案 0 :(得分:0)

您可以做的是在move-item命令中指定-Include *.txt条件,以便仅移动.txt,.log或您要移动的任何文件类型,并保持文件夹的状态不变

答案 1 :(得分:0)

我相信您的代码可以完成一些清理工作。现在您执行了Get-ChildItem 3次,一次使用就足够了。

此外,您应该尝试使用Join-Path而不是自己构造路径和文件名。
特别是在进行"C:\Users\User1\Desktop\MergeTest\_First\$FileInWork"的地方,应该意识到Get-ChildItem返回FileInfo和/或DirectoryInfo 对象;不是字符串。

无论如何,下面的代码应该可以满足您的要求:

# define the path where all other paths are in
$rootPath          = "C:\Users\User1\Desktop\MergeTest"
# create the working paths using the common root folder path
$filesPath         = Join-Path -Path $rootPath -ChildPath '_First'
$firstDestination  = Join-Path -Path $rootPath -ChildPath '___Final'
$secondDestination = Join-Path -Path $rootPath -ChildPath '__Second'

# test if the destination folders exist and if not create them
if (!(Test-Path -Path $firstDestination -PathType Container)) {
    Write-Host "Creating folder '$firstDestination'"
    $null = New-Item -Path $firstDestination -ItemType Directory
}
if (!(Test-Path -Path $secondDestination -PathType Container)) {
    Write-Host "Creating folder '$secondDestination'"
    $null = New-Item -Path $secondDestination -ItemType Directory
}

# get an array of all FileInfo objects in $filesPath
# you could consider adding -Filter '*.xlsx' here..
$allFiles = Get-ChildItem -Path $filesPath -Force -File

Write-Host 'Total number of files found: {0}' -f $allFiles.Count

# move the files
for ($i = 0; $i -lt $allFiles.Count; $i++) {
    if ($i -eq 0) {
        # the first file should go in the $firstDestination folder with specified name
        $target = Join-Path -Path $firstDestination -ChildPath 'TestOutput.xlsx'
    }
    else {
        # all other files go to the $secondDestination folder
        # each file should have the index number as name
        $target = Join-Path -Path $secondDestination -ChildPath ('{0}.xlsx' -f ($i + 1))
    }
    $allFiles[$i] | Move-Item -Destination $target -Force -WhatIf
}

希望有帮助

如果您对控制台上显示的内容感到满意,请删除-WhatIf

P.S。我真的认为您应该编辑问题并更改标题,因为问题与脚本结束后删除文件夹 无关。