簡體   English   中英

復制測試.pdf文件並重命名為目錄中所有當前的.pdf文件

[英]Copy Test .pdf file & rename to all current .pdf files in directory

我需要做的是將test.pdf文件復制為已經在特定目錄中的每個當前.pdf文件。

例如,目錄包含xyz.pdf,rgh.pdf,bne.pdf等。

test.pdf需要重命名為xyz.pdf,rgh.pdf,bne.pdf等。所有.pdf文件都應具有完全相同的內容,這就是為什么我需要將test.pdf重命名為每個.pdf文件。目錄中的pdf文件。

到目前為止,這是我嘗試過的。 它將測試文件“ V2500SB.pdf”復制到正確的目錄。 該目錄中有兩個.pdf文件,但未將“ V2500SB.pdf”重命名為該目錄中的文件。 它在運行第一個文件后也停止運行。 有任何想法嗎?

try
{
$PDFDir = "D:\V2500Test\*"
$items = Get-ChildItem -Path ($PDFDir) 
$ErrorActionPreference= 'continue'
$NewPDFDir = "D:\V2500SB.pdf"
$NewPDF = "V2500SB.pdf"

if (Test-Path -Path "$PDFDir") 
{  

# Code for directory not empty
    # enumerate the items array
    foreach ($item in $items)
    {
     Write-Host $item.Name 
    Copy-Item -Path $NewPDFDir -destination $PDFDir
    Rename-Item $NewPDFDir + $NewPDF $PDFDir + $item -Force

    }
}   
else 
{
Write-Host "No file to move"
 exit
}

} #end of try 
  catch  #Catch any fatal errors and send an email with description
    {
    $ErrorMessage = $_.Exception.Message
    $FailedItem = $_.Exception.ItemName
    $ErrorName = $_.Exception.GetType().FullName  

    $ExceptionBody = @"
    Exception Name: $ErrorName
    Exception Type: $FailedItem 
    Exception Message: $ErrorMessage 
"@

    } # end of catch    
        finally
        {  
        }

您的重命名命令中包含太多內容...

重命名項目$ NewPDFDir + $ NewPDF $ PDFDir + $ item

這就是您要嘗試的...

Rename-Item D:\V2500SB.pdfV2500SB.pdf D:\V2500Test\*whateverWasFound.pdf -Force

同樣,它只復制一次的原因是因為您每次都使用相同的源和目標進行復制...

我強烈建議您嘗試使用有價值的命令,以查看實際發生的情況...

我不清楚您要做什么,但我認為這是兩件事之一:

您是否要用“ test.pdf”的內容替換文件夾中所有文件的內容? 如果是這種情況,您只需要使用Copy-Item,並將目標路徑設置為原始文件名:

$PDFDir = "D:\V2500Test"
$items = Get-ChildItem -Path $PDFDir

$NewPDF = "V2500SB.pdf"

if(Test-Path -Path $PDFDir)
{
    foreach ($item in $items)
    {
        Write-Host $item.Name 
        Copy-Item $NewPDF -Destination $item.FullName
    }
}

還是您要用一個具有另一個文件夾中的文件名但文件名都為'test.pdf的文件填充新文件夾? 在這種情況下,答案是相似的,但是您必須建立一個新路徑(使用Join-Path):

$PDFDir = "D:\SourceFolder"
$items = Get-ChildItem -Path $PDFDir
$NewPDF = "V2500SB.pdf"

$PDFDir2 = "D:\V2500Test"

if(Test-Path -Path $PDFDir2)
{
    foreach ($item in $items)
    {
        Write-Host $item.Name 
        Copy-Item $NewPDF -Destination (Join-Path $PDFDir2 -ChildPath $item.Name) 
    }
}

無論哪種方式,您都不需要先執行Copy-Item然后重命名-Item; Copy-Item可以一步完成。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM