3

I'm trying to delete an existing file on the remote server using WMI.

Here's my code:

string name = @"\\servername\\OCROut\\basketball.txt";

ConnectionOptions options = new ConnectionOptions(remoteServer, "username", "password", "ntlmdomain:domainName", ImpersonationLevel.Impersonate, AuthenticationLevel.Default, true, null, System.TimeSpan.MaxValue);

                            ManagementScope scope = new ManagementScope("\\\\server\\root\\cimv2", options);
                            scope.Connect();
                            var query = new ObjectQuery(string.Format("SELECT * FROM CIM_Datafile WHERE Drive = 'D' AND Name = '{0}' AND Filename = 'basketball' and Extension = 'txt'", name));
                            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
                            var tobeDeleted = searcher.Get();

                            foreach (ManagementObject item in searcher.Get())
                            {
                                item.InvokeMethod("Delete", null);
                            }

The Query is working file but but my Count = 0 when i'm executing the searcher.Get() method. I tried everything, different slashes, without the drive, Filename and extension but nothing seem to be working and i know that the file exists.

Any help would be highly appreciated.

RRUZ
  • 134,889
  • 20
  • 356
  • 483
Arka
  • 31
  • 6

2 Answers2

3

It seems which you are passing wrong values in the params. the Name property must contain the full local path of the file, so try this :

string name = @"D:\\OCROut\\basketball.txt";
var query = new ObjectQuery(string.Format("SELECT * FROM CIM_Datafile WHERE Name = '{0}'", name));
RRUZ
  • 134,889
  • 20
  • 356
  • 483
  • thanks a lot RRUZ...that did work...i guess using the whole server name was creating some issues...thanks adain buddy. – Arka Mar 12 '15 at 17:06
  • How do i accept it? i'm trying to click the up arrow and it says i need 15 reputations? please let me know how and i'll be more than happy to accept it...thanks – Arka Mar 12 '15 at 17:56
0

WMI Script to delete single/multi files in remote server

#for single file

$file = Get-WmiObject -Query "Select * from CIM_Datafile Where Name='c:\\Desktop\\a.txt'" -ComputerName 10.14.34.81 -Credential administrator
if($file)
{
     $file.delete()|out-null
}

#For Multiple files in a directory

$files =  Get-WmiObject -Query "ASSOCIATORS OF {Win32_Directory.Name='c:\Desktop\Temp'} Where ResultClass = CIM_DataFile" -ComputerName 10.14.34.81 -Credential administrator
if($files)
{
    $files|%{$_.Delete()|out-null}
}
Sushena
  • 107
  • 3
  • 8