Help with the copy-item commandlet in Powershell

Greetings Powershell Experts –

I have a folder with 10 files (I’m using .pst files in this instance) in it.  I want to use powershell to select the newest file and copy it to a different folder.  Here is what I thought the code would look like:

Get-childitem c:\source\*.pst | sort-object lastwritetime –descending | select-object –first 1 | copy-item c:\target

When I run this, I get the following error

The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.
At :line:3 char:34
+ Select-Object -First 1 | Copy-Item <<<<  c:\target

I read this as basically saying I can’t pipe input into the copy-item commandlet.  My next thought was to use a variable, so I tried this code:

$item = Get-childitem c:\source\*.pst | sort-object lastwritetime –descending | select-object –first 1

Copy-item $item c:\target

When I do this, the file is copied, but the powershell script looks like its caught in a loop and I have to manually stop it (I’m using PowerGui to write the script).

What am I doing wrong?  Any help would be greatly appreciated.

Thanks in advance,
Nick
LVL 1
ndalmolin_13Asked:
Who is Participating?
 
KenMcFConnect With a Mentor Commented:
Missed pasting some text.

First make sure you have an object, so type this

$item = Get-childitem c:\source\*.pst | sort-object lastwritetime –descending | select-object –first 1

$item

then try what i posted before. What you had should work but might be an issue with powergui
0
 
KenMcFCommented:
Try what you have but add this

Copy-item $item.fullname c:\target
0
 
Dale HarrisProfessional Services EngineerCommented:
I agree with Ken.  I always mess with my code in PowerGui, but actually run it in the Powershell console.
0
 
ndalmolin_13Author Commented:
Thanks for the quick response.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.