Thread: Copy-Item
View Single Post
Old 08-11-2007   #4 (permalink)
Kiron
Guest


 
 

Re: Copy-Item

To work around this bug?/feature? in Copy-Item you can check the existence
of the destination then execute accordingly:

if (test-path c:\test\dest\)
{
copy-item c:\test\src\* c:\test\dest\ -recurse -force
}
else
{
copy-item c:\test\src\ c:\test\dest\ -recurse -force
}

But if you want to save some typing and time, this function will get the
results you expect.
First it deletes the ending asterisk of the source path because if the
destination does not exist Copy-Item ignores the source's child
subdirectory. (If there is no asterisk at the end of the source path it is
unchanged)
Then it checks for the existence of the destination directory, if it exists
the switch statement adds the asterisk to the source path.
Finally Copy-Item gets the right variation of the source path and copies the
child items.

function xCopy
(
[string]$src = $(throw "Specify the source directory"),
[string]$dest = $(throw "Specify the destination diirectory")
)
{
$src = $src -replace '\*$'
if (test-path $dest)
{
switch -regex ($src)
{
'\\$' {$src = "$src*"; break}
'\w$' {$src = "$src\*"; break}
default {break}
}
}
copy-item $src $dest -recurse -force
}

You can call the function like:
xCopy c:\test\src c:\test\dest\
xCopy c:\test\src\ c:\test\dest\
xCopy c:\test\src\* c:\test\dest\

....or minimally naming the parameters (position does not matter)
xCopy -d c:\test\dest\ -s c:\test\src
xCopy -d c:\test\dest\ -s c:\test\src\
xCopy -d c:\test\dest\ -s c:\test\src\*

--
Kiron

My System SpecsSystem Spec