Function - Move-Item

This topic contains 1 reply, has 2 voices, and was last updated by Profile photo of Dave Wyatt Dave Wyatt 3 years, 7 months ago.

  • Author
    Posts
  • #11384
    Profile photo of Toby Williams
    Toby Williams
    Participant

    Hi All,

    I'm in the process of writing up a file archive script but struggling with a function.

    My script should get the files from certain directories and move them to an archive directory, sorting the files into sub directories based on the modified date of each file it moves.

    My script works absolutely fine if I do not use a function and instead pipe straight into Move-Item, this leads me to believe that the problem is with passing some information to the function.

    Here are the script basics:

    Function ArchiveLogs {
    Move-Item -Destination {
    $Save = "$ADir{0:yyyy-MM}" -f $_.LastWriteTime #this builds the destination path
    $Null = mkdir $Save -Force #attempts to create above dir each time, discards all errors
    "$Save\$($_.name)"
    }
    }

    # Log directory, get list of sub directories.
    $LDir = GCI -Path "K:\WebService\test\" | ? {$_.PSIsContainer -AND $LSDirs -contains $_.name}
    # Log sub directories to allow.
    $LSDirs = @("Logs", "OrderExport", "OrdersImport", "StockExport", "StockStatusExport")

    foreach ($Dir in $LDir){
    # Archive to location
    $ADir = "L:\Test\$Dir\Archive\"
    GCI $Dir.fullname | ?{!$_.PSIsContainer} | ArchiveLog
    }

    The error I see is "Move-Item : Cannot evaluate parameter 'Destination' because its argument is specified as a script block and there is no input. A script block cannot be evaluated without input."

    Any help is appreciated.

    Many thanks.

  • #11391
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    I don't really see the advantage to putting the Move-Item command in a function here, since the function only executes the one command and doesn't seem to add any value.

    In any case, as the error message mentions, you can only use a script block as the Destination parameter if you're piping input straight to the Move-Item cmdlet.

You must be logged in to reply to this topic.