这是我的第一次发布,因此对于格式不清楚或不正确的内容,我深表歉意。我会尽力使自己看起来更好。
我正在尝试创建一个Power Shell脚本,该脚本将使用年份和上个月创建一个文件夹。
然后,我只想将某些ext或文件移动到创建的文件夹中。
我现在的问题是Temp或Temp \ files中的任何文本文件都将被移到要创建的文件夹中。
最重要的是,已经移动过一次的文件将在下个月再次移动,并且先前文件夹中的信息将消失。
有什么办法可以将文件夹外部的文件移动到新文件夹中吗?
现在,我的另一个问题是我想创建与文本文档示例相同的日期格式作为前缀:201902-_Name.txt
我还没有弄清楚第二部分,我有点弄清楚了第一部分,除了它在temp中抓取了任何东西并将其移动到它创建的新文件夹中。
# Get the files which should be moved, without folders
$files = Get-ChildItem 'C:\Temp\' -Recurse | where {!$_.PsIsContainer}
# List Files which will be moved
$files
# Target Folder where files should be moved to. The script will automatically create a folder for the year and month.
$targetPath = 'C:\Temp\files\'
foreach ($file in $files){
# Get year and Month of the file
# I used LastWriteTime since this are synced files and the creation day will be the date when it was synced
$year = $file.LastWriteTime.Year.ToString()
$month = (Get-Date).AddMonths(-1).ToString('MM')
$monthname = (Get-Culture).DateTimeFormat.GetAbbreviatedMonthName($month)
# Out FileName, year and month
$file.Name
$year
$month
$monthname
# Set Directory Path
$Directory = $targetPath + "\" + $year + $month
# Create directory if it doesn't exsist
if (!(Test-Path $Directory)){
New-Item $directory -type directory
}
# Move File to new location
$file | Move-Item -Destination $Directory
}
答案 0 :(得分:1)
解决问题#1的最简单方法是将文件移动到源文件夹内 NOT 的目标文件夹中。
如果这不是您想要的,那么您需要为Get-ChildItem
cmdlet添加一个额外的测试,以过滤掉目标文件夹中的所有文件。
类似的事情应该起作用:
$sourcePath = 'C:\Temp\' #'# The folder in which the files to move are
$targetPath = 'C:\Temp\files\' #'# The folder where the files should be moved to
# Get the files which should be moved, without folders and exclude any file that is in the target folder
$files = Get-ChildItem $sourcePath -File -Recurse | Where-Object { $_.FullName -notlike "$targetPath*" }
# for PowerShell version below 3.0 use this:
# $files = Get-ChildItem 'C:\Temp\' -Recurse | Where-Object {!$_.PsIsContainer -and $_.FullName -notlike "$targetPath*"}
# List Files which will be moved
# $files
foreach ($file in $files){
# Get year and Month of the file
# I used LastWriteTime since this are synced files and the creation day will be the date when it was synced
$year = $file.LastWriteTime.Year
$month = (Get-Date).AddMonths(-1).ToString('MM') # last month from current date
$monthname = (Get-Culture).DateTimeFormat.GetAbbreviatedMonthName($month)
# Out FileName, year and month
# $file.Name
# $year
# $month
# $monthname
$dateString = '{0}{1}' -f $year, $month
# Set Directory Path
$Directory = Join-Path -Path $targetPath -ChildPath $dateString
# Create directory if it doesn't exsist
if (!(Test-Path $Directory -PathType Container)){
New-Item $Directory -ItemType Directory | Out-Null
}
# Move File to new location and prepend the date prefix to its name
$targetFile = Join-Path -Path $Directory -ChildPath ('{0}-{1}' -f $dateString, $file.Name)
$file | Move-Item -Destination $targetFile -Force
}
如您所见,通过使用相同的$ dateString变量,Move-Item
cmdlet不仅可以移动,还可以重命名文件。
希望这会有所帮助