Razort4x
Razort4x

Reputation: 3416

copy not picking up correct source folder

I have this script

$folder = Get-ChildItem -Path \\exp-01\Uploads |
          Sort-Object LastWriteTime -Descending |
          Select-Object -Last 1

The folder variable is correctly set up, when I check it, it comes up as

    Directory: \\exp-01\Uploads


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----        29/05/2017     08:17            149604223125762

But when I do this

copy $folder E:\InvoiceUploads\files\ -Recurse

I get an error,

copy : Cannot find path 'C:\Users\web.developer.03\149604223125762' because it does not exist.

The PowerShell is running the folder (the prompt is):

C:\Users\web.developer.03>

So, basically it it not picking up correct source, instead it is taking up the current directory as the source. What am I doing wrong here?

Upvotes: 1

Views: 55

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200523

$folder contains a DirectoryInfo object, not a path. By default PowerShell expands the Name property of these objects, so Copy-Item is looking for the folder name in the current working directory.

Either expand the FullName property when selecting the folder:

$folder = Get-ChildItem -Path \\exp-01\Uploads |
          Sort-Object LastWriteTime -Descending |
          Select-Object -Last 1 -Expand FullName

or use the FullName property in the Copy-Item statement:

copy $folder.FullName E:\InvoiceUploads\files\ -Recurse

Upvotes: 2

Seems like you're using the MS CMD syntax. (Notice you're using Copy - not Copy-Item)

Did you try and use Powershells cmdlet for copying, along with named parameters for source and destination? Perhaps it helps you.

SYNTAX
    Copy-Item [-Path] <String[]> [[-Destination] <String>] [-Container] [-Credential <PSCredential>] [-Exclude <String[
    ]>] [-Filter <String>] [-Force] [-Include <String[]>] [-PassThru] [-Recurse] [-Confirm] [-WhatIf] [-UseTransaction
    [<SwitchParameter>]] [<CommonParameters>]

    Copy-Item [[-Destination] <String>] [-Container] [-Credential <PSCredential>] [-Exclude <String[]>] [-Filter <Strin
    g>] [-Force] [-Include <String[]>] [-PassThru] [-Recurse] -LiteralPath <String[]> [-Confirm] [-WhatIf] [-UseTransac
    tion [<SwitchParameter>]] [<CommonParameters>]

Upvotes: -1

Related Questions