Poweshell to connect to remote machine and Copy-Item issues

Hi,

I have below two queries.

Query1:
My requirement is to establish a connection with a remote machine and copy the folders into one of its drive. Despite running the powershell in administrator mode, I am still prompted to give the password. is my below command correct , please verify and let me know.

Invoke-Command -ComputerName \\ -ScriptBlock { Get-ChildItem C:\ } -credential get-credential

Query2:
While performing the copy-item (nested), one of the files in the subfolder is being copied in the root folder too. Ideally, the structure along with the files and subfolders should be copied in a consistent manner. I am excluding few folders from being copied.
Scenario:
Source has the below structure.
Rootfolder>Subfolder1>Subfolder1_1>demo.txt
Rootfolder>Subfolder2
Rootfolder>Subfolder3
Rootfolder>sample.txt

after running the below command:-

$ExcludeFolders = @(“subfolder2”)
Get-ChildItem -Path $FROM -Exclude $ExcludeFolders |
Copy-Item -Destination $TO -force -recurse

The destination folder is coming up this way:
Rootfolder>Subfolder1>Subfolder1_1>demo.txt
Rootfolder>Subfolder3
Rootfolder>sample.txt
Rootfolder>demo.txt

please answer my above two queries

Thanks,
laxman

If all you want to do see if a folder does not exist and copy a folder structure, I would simplify your approach:

$servers = "server1", "server2", "server3"
$sourceFolder = "C:\Source\ItsFriday"

foreach ($server in $servers) {
    $destinationFolder = "{0}\c$\ItsFriday" -f $server
    if (-not (Test-Path -Path $destinationFolder)) {
        Copy-Item -Path $sourceFolder -Destination $destinationFolder -Recurse
    }
}

As far as your second query, is something not working? You show that you want to exclude a folder and that the folder is excluded.

Hi Mr.Simmers,

Thanks for the response.

I’ll implement and cross check the fix given by on query 1.
(one question on this - WHEN THE POWER SHELL IS RUN IN ADMINISTRATOR MODE, STILL IS IT REQUIRED TO FURNISH THE ADMIN’s PASSWORD WHILE ESTABLISHING THE CONNECTION WITH ANY NETWORK MACHINE OR REMOTE SERVER MACHINE?)

As far as the second query is concerned, I am able to exclude the required folders and files while performing the copy-item. However, what is bothering me is , one of the file(s) from 2nd level sub folder is being copied into the root folder too.

In my above sample, ‘demo.txt’ is the file that is residing in ‘Subfolder1_1’ which is in ‘Subfolder1’ and in turn this folder is in ‘Root’ folder.But when the script is run, I could see the demo.txt file being copied in ‘Root’ folder too. (Root>demo.txt). Which means, the file ‘demo.txt’ is existing in its original folder (SubFolder1_1) as well as in ‘Root’ folder.