问题
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.
回答1:
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));
回答2:
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}
}
来源:https://stackoverflow.com/questions/28998362/delete-file-on-remote-server-using-wmi