CodeMaster
CodeMaster

Reputation: 31

Copying files containing particular key words, and moving them to another folder, with Powershell

I have stored file paths which match particular text which I am looking for, in a variable called $filepaths. Now, what I want to do is copy those files, which match content I'm looking for, and put them into a new folder, with say, file path: C:\newfolder

I have written the following simple scripts, neither of which work:

1.

Copy-Item -path $match in $filepaths -Destination C:\newfolder -Recurse

2.

foreach($match in $filepaths)
{
    Copy-Item -path $match -Destination C:\newfolder
}

I converted the file paths into a table format using $filepaths = $files | Format-Table * -wrap (which works) - but perhaps this is what is causing the problem?

Where am I going wrong here?

Upvotes: 1

Views: 259

Answers (1)

Matt
Matt

Reputation: 46710

AHHHH the Format-.... problem

Never use Format-Anything if you intend to use the data again. You have corrupted the object you had by saving the table format.

I don't know what $files is but if it is output from Get-ChildItem then leave it be and you will be fine. Same goes if it was just a string array.

Look at the following examples

Proper Output

Get-ChildItem c:\temp | Get-Member would give you a potential mix of System.IO.DirectoryInfo and System.IO.FileInfo objects.

"Corrupted" Output

Get-ChildItem c:\temp | Format-Table | Get-Member would give you objects like the following. There are more than this but point is the original objects are gone.

Microsoft.PowerShell.Commands.Internal.Format.GroupStartData
Microsoft.PowerShell.Commands.Internal.Format.FormatStartData
Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData
 ....

Upvotes: 2

Related Questions