使用Powershell脚本移动文件,但移动脚本本身-如何解决?

时间:2019-03-04 14:38:49

标签: powershell move

我有以下脚本将单个目录中的大量文件拆分为多个子文件夹,并进行拆分以使子文件夹的大小/文件数易于管理。它可以工作,但是有两个小问题我想解决:

# First count the number of files in the $OrigFolder directory
$numFiles = (Get-ChildItem -Path $OrigFolder).Count
$i=0

#Calculate copy operation progress as a percentage
[int]$percent = $i / $numFiles * 100

$n = 0; Get-ChildItem -File | Group-Object -Property {$script:n++; 
[math]::Ceiling($n/9990)} | 
ForEach-Object {                               
    $dir = New-Item -Type Directory -Name $_.Name   # Create directory
    $_.Group | Move-Item -Destination $dir          # Move files there

# Log progress to the screen
Write-Host "$($_.FullName) -> $FolderName"

# Tell the user how much has been moved
Write-Progress -Activity "Copying ... ($percent %)" -status $_  -PercentComplete             
$percent -verbose
$i++
    }

首先,如何防止脚本本身移动到第一个脚本创建的子文件夹?

第二,如何在脚本创建的文件夹之前添加名称“ Move Files”?现在,它们只是按顺序编号。

2 个答案:

答案 0 :(得分:1)

通过检查$MyInvocation来排除脚本本身:

$n = 0; Get-ChildItem -File |Where-Object {$_.FullName -ne $MyInvocation.InvocationName} | Group-Object -Property { ...

调用New-Item创建目录时,可以在-Name参数前添加所需的内容:

$dir = New-Item -Type Directory -Name "Move Files $($_.Name)"   # Create directory

答案 1 :(得分:1)

对于那些需要工作脚本并且不想自己进行更改的人,这里是工作版本

# MOVE FILES TO FOLDERS
#
# When placed in a parent directory, this Powershell script moves a large number of files (e.g., > 10,000)
# to subdirectories in batches of xxx files. In the case here, in batches of 9,990 files to each
# subdirectory.
# Edit the item in the script ($n/9990) to change the breakpoint for your needs.
# Thanks to  Mathias R. Jessen on StackOverflow for helping with the code.
#

# BEGIN SCRIPT
# First count the number of files in the $OrigFolder directory
$numFiles = (Get-ChildItem -Path $OrigFolder).Count
$i=0

#Calculate copy operation progress as a percentage
[int]$percent = $i / $numFiles * 100

$n = 0; Get-ChildItem -File | Where-Object {$_.FullName -ne $MyInvocation.InvocationName} | Group-Object -Property {$script:n++; 
[math]::Ceiling($n/9990)} | 
ForEach-Object {                               
    $dir = New-Item -Type Directory -Name $_.Name "Move Files $($_.Name)"  # Create directory
    $_.Group | Move-Item -Destination $dir          # Move files there

# Log progress to the screen
Write-Host "$($_.FullName) -> $FolderName"

# Tell the user how much has been moved
Write-Progress -Activity "Copying ... ($percent %)" -status $_  -PercentComplete
$percent -verbose
$i++
    }

# END SCRIPT

感谢@ mathias-r-jessen对代码的帮助。