Quantcast
Channel: WMI – PowerShell for Windows Admins
Viewing all articles
Browse latest Browse all 140

CIM snippets–working with file system

$
0
0

The latest instalment from the WMI team on using PowerShell and the CIM cmdlets is available – http://blogs.msdn.com/b/wmi/archive/2014/03/28/performing-management-tasks-using-cim-cmdlets-4-files-and-folders.aspx

This time round the examples are to do with working with the file system – files, folders and shares.

If you’ve worked with WMI you’ll be aware of that very often you get 2 classes one with a prefix of CIM (base class from DMTF definition) and one with Win32 prefix which is the Microsoft implementation. They 2 classes are often identical though the Win32 class may have additions.

The WMI class for working with files is different – it only has a CIM version CIM_DataFile.

The first example in the post is about renaming a file. A much simpler coding of the task would be:

Get-CimInstance -ClassName CIM_Datafile -Filter “Name = ‘C:\\Test\\Names.txt’” | Invoke-CimMethod -MethodName Rename -Arguments @{FileName = ‘C:\\Test\\OldNames.txt’}

A couple of points to note:

- when dealing with file paths all \ characters must be doubled. This is because \ is a WMI escape character so you need to escape it to use it literally.

- Invoke-CimMethod uses a hash table for the method arguments with the argument name as the key – this takes away any of the argument order issues you see with Invoke-WmiMethod)

One perennial problem for administrators is users putting their own files on the organization’s file servers.  Want to know if there any files of a specific type in a folder?

Get-CimInstance -ClassName CIM_Datafile -Filter “Extension = ‘txt’ AND Path = ‘\\test\\’”

If you leave the path out of the filter then all files on the drive will be searched – could take a while.  Being specific in your filter will save you a lot of time.

Want to find all the mp3 files on a drive?

Get-CimInstance -ClassName CIM_Datafile -Filter “Extension = ‘mp3′”

You can’t create files and folders with CIM (or WMI) but you can create shares

 

$margs = @{
Path = ‘C:\Test’
Name = ‘Test2April’
Description = ‘TestShare’
Type = [uint32]0
}

Invoke-CimMethod -ClassName Win32_Share -MethodName Create -Arguments $margs

Create the hash table of arguments separately  – its easier to read. Bizarrely this time you don’t need to escape the \ in the path

You can see the shares on a system like this:

Get-CimInstance -ClassName Win32_Share

CIM may not be you first port of call when working with the file system but it can be useful – especially on remote systems.

You can find out much more about using CIM to work with the file system in chapetr 8 of PowerShell and WMI – www.manning.com/siddaway2


Viewing all articles
Browse latest Browse all 140

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>