使用WMI删除远程服务器上的文件

时间:2015-03-11 22:10:53

标签: c# wmi wmi-query

我正在尝试使用WMI删除远程服务器上的现有文件。

这是我的代码:

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);
                            }

Query正在运行文件,但是当我执行searcher.Get()方法时,我的Count = 0。我尝试了所有的,不同的斜杠,没有驱动器,文件名和扩展名,但似乎没有任何工作,我知道该文件存在。

任何帮助都将受到高度赞赏。

2 个答案:

答案 0 :(得分:3)

似乎你在params中传递了错误的值。 Name属性必须包含文件的完整本地路径,因此请尝试以下操作:

string name = @"D:\\OCROut\\basketball.txt";
var query = new ObjectQuery(string.Format("SELECT * FROM CIM_Datafile WHERE Name = '{0}'", name));

答案 1 :(得分:0)

用于删除远程服务器中的单个/多个文件的WMI脚本

#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目录中的多个文件

$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}
}