Reputation: 1574
I have a simple task of getting a file from one path and copying it to another using PowerShell script. Now, I understand that using Get-ChildItem
, if-Path
is not specified, it will get the current directory. I'm using this code, setting the directory the file is in, but it is still getting the current directory:
$file = Get-ChildItem -Path "\\w102xnk172\c$\inetpub\wwwroot\PC_REPORTS\exemplo\DCT\Files\STC" | Sort-Object LastWriteTime | Select-Object -Last 1
Copy-Item $file -Destination "\\Brhnx3kfs01.vcp.amer.dell.com\brh_shipping$\DEMAND_MONITOR\"
cmd /c pause | out-null
It returns this error when it pauses:
This is script follow the rules in the documentation of both Get-ChildItem and Copy-Item. Am I missing something? Why is it still getting the current directory? I tried mutiple syntaxes differences, getting the paths out of commas, not setting -Path or -Destination, setting the file directly in the Copy-Item without using the $file
variable...
Upvotes: 0
Views: 6908
Reputation: 174465
Copy-Item
expects a [string]
as the first positional argument - so it attempts to convert $file
to a string, which results in the name of the file.
Either reference the FullName
property value (the full path) of the file:
Copy-Item $file.FullName -Destination "\\Brhnx3kfs01.vcp.amer.dell.com\brh_shipping$\DEMAND_MONITOR\"
Or pipe the $file
object to Copy-Item
and let pipeline binding do its magic for you:
$file |Copy-Item -Destination "\\Brhnx3kfs01.vcp.amer.dell.com\brh_shipping$\DEMAND_MONITOR\"
If you want to see for yourself how this is processed internally by powershell for yourself, use Trace-Command
:
Trace-Command -Name ParameterBinding -Expression {Copy-Item $file -Destination "\\Brhnx3kfs01.vcp.amer.dell.com\brh_shipping$\DEMAND_MONITOR\"} -PSHost
Upvotes: 2