使用PowerShell移动文件

c90pui9n  于 2023-06-06  发布在  Shell
关注(0)|答案(1)|浏览(156)

下面是Powershell脚本。
目的是让脚本在源文件夹中查找特定的图形文件,并将其移动到另一个文件夹。
该脚本还被设计为检查文件是否已经被复制并跳过这些文件。
该脚本运行它生成一个文本文件的文件列表,但为空,也不复制任何文件。
最后我希望它能在任务调度器中运行

# Set variables
$sourceFolder = "C:\mysource\folder"
$destinationFolder = "C:\mydestination\folder"
$extensionFilter = "*.hdf"
$zipFileName = "New_Drawings_$(Get-Date -Format 'yyyy-MM-dd').zip"
$processedFilesFile = "C:\mydestination\folder\myProcessedFiles.txt"

# Check if the processed files file exists and create it if it doesn't
if (!(Test-Path $processedFilesFile)) {
    New-Item -Path $processedFilesFile -ItemType File
}

# Get the list of files that match the extension filter in the source folder and its        subfolders and haven't been processed before
$fileList = Get-ChildItem -Path $sourceFolder -Recurse -Filter $extensionFilter | Where-Object {!($_.PSIsContainer) -and $_.LastWriteTime.Date -eq (Get-Date).AddDays(-1).Date -and (Get-Content $processedFilesFile) -notcontains $_.Name}

# Check if any files were found
if ($fileList.Count -gt 0) {
    # Create a new zip file with yesterday's date in the name
    $zipFileName = "New_Drawings_$(Get-Date).AddDays(-1).ToString('yyyy-MM-dd').zip"
    $zipFilePath = Join-Path $destinationFolder $zipFileName
    Compress-Archive -Path $fileList.FullName -DestinationPath $zipFilePath

    # Move the zip file to the source folder
    $zipFile = Get-Item -Path $zipFilePath
    $destinationPath = Join-Path $sourceFolder $zipFileName
    Move-Item -Path $zipFile.FullName -Destination $destinationPath

    # Add the names of the processed files to the processed files file
    $fileList.Name | Out-File $processedFilesFile -Append
}

我的代码是否有问题,或者可能与权限问题有关?有很多符合标准的文件,我也尝试了其他文件扩展名,仍然不起作用
预先感谢任何帮助

cngwdvgl

cngwdvgl1#

问题是你的日期比较,特别是你有

$_.LastWriteTime.Date -eq (Get-Date).AddDays(-1).Date

而Get-Date部分将返回:
2019 - 05 - 23 00:00:00
LastWriteTime.Date行将返回文件修改日期的日期和时间。
因此,而不是-eq,你需要-ge来捕捉所选日期午夜之后的所有时间。就像这样

$fileList = Get-ChildItem -Path $sourceFolder -Recurse -Filter $extensionFilter | Where-Object {!($_.PSIsContainer) -and $_.LastWriteTime.Date -ge (Get-Date).AddDays(-1).Date -and (Get-Content $processedFilesFile) -notcontains $_.Name}

这就是为什么如果您尝试输出$filelist,您会发现它是空的,因为没有文件符合这些条件。

相关问题