Author Posts

March 22, 2017 at 2:25 am

I'm perplexed by the way Copy-Item is behaving under different circumstances.
When I use the following:

dir C:\Windows\Microsoft.NET\assembly\GAC_MSIL\ -Filter "PrefixOfFileName.*" -Recurse |foreach {Copy-Item $_.FullName C:\Temp\assemblies}

I get a new folder created in C:\Temp\assemblies. However inside this folder I get empty folders that also match "PrefixOfFileName.*"

So I tried the following:

dir C:\Windows\Microsoft.NET\assembly\GAC_MSIL\PrefixOfFoldersContainingDLLs.* -Filter "*.dll" -Recurse |foreach {Copy-Item $_.FullName C:\Temp\assemblies}

This does not create a new folder, it creates one file called assemblies. When I remove the foreach it lists all the dlls I am expecting. So I'm unclear why the new folder isn't created and only a single file with the name of the folder I am expecting to hold all the dlls.

How can I just copy the dlls that begin with a certain string followed by a wildcard and none of the folders while creating the C:\Temp\assemblies folder when it doesn't exist?

March 22, 2017 at 6:06 am

# copy the dlls that begin with a certain string followed by a wildcard and none of the folders 
# while creating the C:\Temp\assemblies folder when it doesn't exist

$Prefix       = 'Presentation'
$SearchRoot   = 'C:\Windows\Microsoft.NET\assembly\GAC_MSIL\'
$TargetFolder = 'C:\Temp\assemblies'

if (! (Test-Path $TargetFolder)) { New-Item $TargetFolder -Type Directory }
Get-ChildItem $SearchRoot -Filter "$Prefix*.*" -Recurse -File | % { 
    Copy-Item $_.FullName $TargetFolder 
}

March 22, 2017 at 1:09 pm

Thanks Sam for the clean and clear example. I am just learning powershell so I was having fun trying to accomplish the task in one line.

According to the documentation for Copy-Item it says on this example:

Copy-Item C:\Logfiles -Destination C:\Drawings\Logs -Recurse

This command copies the contents of the C:\Logfiles directory to the C:\Drawings\Logs directory. It creates the \Logs subdirectory if it does not already exist.

So I was expecting the directory to be created automatically if it didn't exist.

In my first try from my original post the directory was automatically created (but with more than I wanted in it).
My second try would return just what I wanted but create a single file with the name of the directory I wanted.

Can you help me understand why a file is being created where I'm expecting a folder to be created? Thanks!