PowerShell for Windows Admins

Feb 18 2015   1:31PM GMT

Copy a file with WMI

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:
CIM
Powershell
WMI

A question came up on the forum about copying files with CIM (WMI). I normally use Copy-Item rather than CIM as its easier. The questioner was using CIM_LogicalFile when I’ve normally used CIM_DataFile so I decided to take a look at the class. In reality the two classes are very similar and CIM-datafile could be substituted for CIM_LogicalFile in the code that follows.

The obvious starting point is to use the Copy method on the CIM_LogicalFile class

$files = Get-WmiObject -Class CIM_LogicalFile -Filter “Path = ‘\\Test\\’ AND Extension = ‘txt'”

foreach ($file in $files) {
$newfile = “C:\Test2\$($file.FileName).$($file.Extension)”

$file.Copy($newfile)

}

Couple of points to note. In the Path part of the filter you have to escape the \ delimiter.  Extension doesn’t include the ‘.’

You have to give the full path – including file name – to the loaction to which you want to copy the file. In this case you don’t have to escape the \ delimiter. Consistency is a wonderful thing and usually absent from WMI.

You can also use Invoke-WmiMethod

$files = Get-WmiObject -Class CIM_LogicalFile -Filter “Path = ‘\\Test\\’ AND Extension = ‘txt'”

foreach ($file in $files) {
$newfile = “C:\Test2\$($file.FileName).$($file.Extension)”

Invoke-WmiMethod -InputObject $file  -Name Copy -ArgumentList $newfile

}

OR

use the new CIM cmdlets

$files = Get-CimInstance -ClassName CIM_LogicalFile -Filter “Path = ‘\\Test\\’ AND Extension = ‘txt'”

foreach ($file in $files) {
$newfile = “C:\Test2\$($file.FileName).$($file.Extension)”

Invoke-CimMethod -InputObject $file  -MethodName Copy -Arguments @{Filename = $newfile}

}

In this case you have to give the argument name for the method as well as its value. You can discover the method parameters using Get-CimClass

$class = Get-CimClass CIM_LogicalFile

£> $class.CimClassMethods[“Copy”].Parameters

2  Comments on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.
  • poster
    Regarding your CIM meathod. Can I just add -CimSession $CimSession to Get-CimInstance and do copy files remotely? When I try it I get ReturnValue : 9 (Invalid name).
    0 pointsBadges:
    report
  • Richard Siddaway
    You can't copy files over a CIM session - just a PS remoting session
    9,575 pointsBadges:
    report

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: