|
Sorry, i didn't want people to think i wanted them to do all my work for me.... but if your offering!
cls
$ErrorActionPreference = "SilentlyContinue"
$servers = Get-Content c:\Temp\servers.txt
foreach($srv in $servers)
{
try
{
$ID = New-Object System.Security.Principal.NTAccount("AccountName")
$SID = $ID.Translate([system.Security.Principal.SecurityIdentifier]).ToString()
$WMISDDL = "A;CI;CCWP;;;" + $SID
$WMISDDLPartialMatch = "A;\w*;\w+;;;" + $SID
$security = Get-WmiObject -ComputerName $srv -Namespace root -Class __SystemSecurity
$binarySD = @($null)
$result = $security.PsBase.InvokeMethod("GetSD",$binarySD)
write-host "`tConverting current permissions to SDDL format..."
$converter = new-object system.management.ManagementClass Win32_SecurityDescriptorHelper
$CurrentWMISDDL = $converter.BinarySDToSDDL($binarySD[0])
write-host "`tBuilding the new permissions..."
if (($CurrentWMISDDL.SDDL -match $WMISDDLPartialMatch) -and ($CurrentWMISDDL.SDDL -notmatch $WMISDDL))
{
$NewWMISDDL = $CurrentWMISDDL.SDDL -replace $WMISDDLPartialMatch, $WMISDDL
}
else
{
$NewWMISDDL = $CurrentWMISDDL.SDDL += "(" + $WMISDDL + ")"
}
# Convert SDDL back to Binary
write-host `t"Converting SDDL back into binary form..."
$WMIbinarySD = $converter.SDDLToBinarySD($NewWMISDDL)
$WMIconvertedPermissions = ,$WMIbinarySD.BinarySD
# Apply the changes
write-host "`tApplying changes..."
if($CurrentWMISDDL.SDDL.ToString().Contains($WMISDDL.ToString()))
{
write-host "`tCurrent WMI Permissions matches desired value..."
}
else
{
$result = $security.PsBase.InvokeMethod("SetSD",$WMIconvertedPermissions)
if($result='0'){write-host "`t`tApplied WMI Security complete."}
}
}
catch
{
Write-Host $Error[$Error.Count - 1].ToString()
}
}
Write-Host "`nFinished" -ForegroundColor DarkBlue
modified on Thursday, February 24, 2011 7:29 AM
|
|
|
|
|
Surround your code with <pre></pre> tags so it is readable.
I must get a clever new signature for 2011.
|
|
|
|
|
ok, i have done this now.
|
|
|
|
|
Philip Lane wrote: does anyone know of a way / programme to convert Powershell scripts into C# code?
Read a line of the script, and translate/convert it to C#. It's a manual proces where you interpret what the script should do, and write some code that does the same.
Philip Lane wrote: i have a short script that i need to convert and it is proving pretty tricky!
Can you point out where you're stuck with translating?
I are Troll
|
|
|
|
|
Hi Eddy,
the big problem is witht he casting. in PS it automatically decides what object type it needs to be but in C# it need to be specified. the code below compiles but line 11 errors saying - "Invalid parameter"
any help would be great thanks.
here is what i have so far:
InvokeMethodOptions imo = new InvokeMethodOptions();
imo.Timeout = new TimeSpan(0, 0, 0, 5);
NTAccount ID = new NTAccount(uName);
string SID = ID.Translate(typeof(SecurityIdentifier)).ToString();
string WMISDDL = "A;CI;CCWP;;;" + SID;
string WMISDDLPartialMatch = "A;\\w*;\\w+;;;" + SID;
ManagementClass security = new ManagementClass(new ManagementPath("\\\\" + server + "\\root\\Security:__SystemSecurity"));
object BinarySD = null;
ManagementBaseObject result = (ManagementBaseObject)security.InvokeMethod("GetSD", (ManagementBaseObject)BinarySD, imo);
ManagementClass converter = new ManagementClass("\\\\" + server + "\\root\\CIMV2:Win32_SecurityDescriptorHelper");
ManagementBaseObject CurrentWMISDDL = (ManagementBaseObject)converter.InvokeMethod("BinarySDToSDDL", (ManagementBaseObject) BinarySD, imo);
string NewWMISDDL;
if (CurrentWMISDDL.Properties["SDDL"].ToString() == WMISDDLPartialMatch && CurrentWMISDDL.Properties["SDDL"].ToString() != WMISDDL)
{
NewWMISDDL = CurrentWMISDDL.Properties["SDDL"].ToString().Replace(WMISDDLPartialMatch, WMISDDL);
}
else
{
NewWMISDDL = CurrentWMISDDL.Properties["SDDL"].ToString() + "(" + WMISDDL +")";
}
ManagementObject WMIBinarySD = (ManagementObject)converter.InvokeMethod("SDDLToBinarySD", new object[] { NewWMISDDL });
ManagementBaseObject WMIConvertedPerms = (ManagementBaseObject)WMIBinarySD.Properties["BinarySD"].Value;
if (CurrentWMISDDL.Properties["SDDL"].ToString().Contains(WMISDDL.ToString()))
{
Console.WriteLine("Current WMI permissions already match desired value.");
}
else
{
result = (ManagementObject)security.InvokeMethod("SetSD", new object[] { WMIConvertedPerms });
if ((Int32)result.GetPropertyValue("ReturnValue") == 0)
{
Console.WriteLine("Applied WMI security permissions.");
}
else
{
Console.WriteLine("Error applying permissions!");
}
}
}
catch (Exception exp)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Error: " + exp.Message.ToString());
Console.ResetColor();
}
Many Thanks,
Phil
|
|
|
|
|
That'd be this line;
ManagementBaseObject CurrentWMISDDL = (ManagementBaseObject)converter.InvokeMethod("BinarySDToSDDL", (ManagementBaseObject) BinarySD, imo);
Would that be the invocation of this[^] method? Seems to return an uint32 according to the documentation, taking two parameters.
Take care that you copy the correct version of all the references that the script is using.
I are Troll
|
|
|
|
|
tried that.. didn't work!
says it cant convert it, and other parts of the programme fail!
|
|
|
|
|
Philip Lane wrote: tried that.. didn't work! says it cant convert it
Compile-time or run-time?
Break up the statement into smaller pieces, so that you can check the assignment, the cast and the invoking of the function separately.
I are Troll
|
|
|
|
|
run-time.
i have tried what you suggested and it all looks fine!
|
|
|
|
|
Hi,
I am designing simple Calculator. And TextBox contains "300+500-10" values.
Kindly let me know, how may I calculate it from TextBox ? or Let me know another method.
Thank you
(Riaz)
|
|
|
|
|
Follow the link below:
http://www.codeproject.com/KB/recipes/MathieuMathParser.aspx?artkw=evaluate expression
Hope this will help.
|
|
|
|
|
Thanks for Helping friend
|
|
|
|
|
If you look above the text box when you enter a reply, there are two "link" widgets.
If you highlight your link, and press one of the widgets, it converts the link to a clickable link: easier for people to use, and looks better!
Your original:
http://www.codeproject.com/KB/recipes/MathieuMathParser.aspx
First "link"
An extensible math expression parser with plug-ins
Second "link[^]" (It gives a "new window/tab" option to the link)
An extensible math expression parser with plug-ins[^]
Much prettier!
Real men don't use instructions. They are only the manufacturers opinion on how to put the thing together.
Digital man: "You are, in short, an idiot with the IQ of an ant and the intellectual capacity of a hose pipe."
|
|
|
|
|
Thanks for pointing it out.
Will use it next time.
|
|
|
|
|
Welcome!
Real men don't use instructions. They are only the manufacturers opinion on how to put the thing together.
Digital man: "You are, in short, an idiot with the IQ of an ant and the intellectual capacity of a hose pipe."
|
|
|
|
|
|
Hi,
I am trying to delete some nodes from an xml document. I am using LINQ to xml and want to stick to this approach. Here is my XML document:
<?xml version="1.0" encoding="utf-8"?>
<Project>
<Clips>
<Clip ID="1" Sequence="1">
<Name></Name>
<Description></Description>
<Location></Location>
<Duration></Duration>
<Images>
<Image ID="1">
<Name></Name>
<Description></Description>
<Location></Location>
<StartTime></StartTime>
<EndTime></EndTime>
</Image>
</Images>
</Clip>
<Clip ID="2" Sequence="1">
<Name>Bazingaaa</Name>
<Description>Masdljaslda</Description>
<Location>C:\Videos</Location>
<Duration>00:00:30</Duration>
<Images>
<Image ID="1">
<Name>Faheem</Name>
<Description>MyImage</Description>
<Location>C:\Images</Location>
<StartTime>00:00:00</StartTime>
<EndTime>00:00:10</EndTime>
</Image>
<Image ID="2">
<Name>Fawaz</Name>
<Description>MyImage</Description>
<Location>C:\Images</Location>
<StartTime>00:00:00</StartTime>
<EndTime>00:00:10</EndTime>
</Image>
</Images>
</Clip>
</Clips>
</Project>
I have to perform two cases. 1. Delete clip node based on ID. 2. Clear whole project root tag.
I am using the following code to delete nodes.
IEnumerable<XElement> clip = (from c in this.oProjectDoc.Element("Project").Element("Clips").Elements("Clip")
where c.Attribute("ID").Value.Equals(ID)
select c);
foreach (XElement xe in clip)
xe.Remove();
this.oProjectDoc.Save(this.oProjectPath.FullName);
Have tried this as well.
var q = from node in oProjectDoc.Root.DescendantsAndSelf("Clips")
let attr = node.Attribute("ID")
where attr != null && attr.Value == clipId
select node;
q.ToList().ForEach(x => x.Remove());
oProjectDoc.Save(this.oProjectPath.FullName);
Problem happens when i try to delete the last clip node or the clear the whole root "Project" tag. I get a lingering end node tag. Like:
</Clip>
Any solutions to that. Kindly please also tell me how can clear all my nodes from xml document. i.e. totally empty my xml document and start afresh without deleting the xml file.
Thanks in advance
Regards...
|
|
|
|
|
Instead of this:
var q = from node in oProjectDoc.Root.DescendantsAndSelf("Clips")
let attr = node.Attribute("ID")
where attr != null && attr.Value == clipId
select node;
q.ToList().ForEach(x => x.Remove());
Why can't you do this:
var q = (from node in oProjectDoc.Root.DescendantsAndSelf("Clips")
let attr = node.Attribute("ID")
where attr != null && attr.Value != clipId
select node);
oProjectDoc.Root.RemoveAll();
foreach(XElement element in q)
{
oProjectDoc.Root.Add(element);
}
".45 ACP - because shooting twice is just silly" - JSOP, 2010 ----- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010 ----- "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass." - Dale Earnhardt, 1997
|
|
|
|
|
Hi,
will u tell me, how can i display an warning message to the user if the file he/she is uploading is open in his machine..
In my Application, i can upload only a file of type *.txt or *.csv,
so could u tell me how can i display a message to the user, when he is uploading a file of (.txt or .csv)type only when that particular file is open in his machine..
As of now in my application, it makes the application crash if that uploading file is open in user machine..
please check my code here..
private void BtnBrowseClick(object sender, RoutedEventArgs e)
{
OpenFileDialog file1 = new OpenFileDialog { Multiselect = false, Filter = "All Supported Files |*.txt;*.csv|Text|*.txt|CSV |*.csv"};
if (file1.ShowDialog() == true)
{
new FileInfo(file1.FileName);
try
{
using (Stream str = file1.OpenFile())
{
TextReader reader = new StreamReader(str);
reader.ReadToEnd();
txtFileName.Text = file1.FileName;
txtFileName.IsEnabled = false;
}
}
catch
{
txtFileName.Text = file1.FileName;
txtFileName.IsEnabled = false;
MessageBox.Show("Please check the file has been Closed before you upload", "Manual File Upload");
}
}
}
It is showing warning message if i change the permission of that file(.txt or .csv) or if i dint changed the permission, it is not showing any warning message, could u tell me how can i do it in a right way..
If possible tell me with a sample code, so i change my code or alter it...
Thanks
|
|
|
|
|
There is a hack using a Try Catch Block and catching an IOException . In your case you could do something like this,
private void BtnBrowse_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog file1 = new OpenFileDialog { Multiselect = false, Filter = "All Supported Files |*.txt;*.csv|Text|*.txt|CSV |*.csv" };
if (file1.ShowDialog() == true)
{
new FileInfo(file1.FileName);
using (Stream str = file1.OpenFile())
{
try
{
System.IO.FileStream fs = System.IO.File.OpenWrite(file1.FileName);
fs.Close();
}
catch (IOException)
{
MessageBox.Show("Please check the file has been Closed before you upload", "Manual File Upload");
return;
}
TextReader reader = new StreamReader(str);
reader.ReadToEnd();
textBox1.Text = file1.FileName;
textBox1.IsEnabled = false;
}
}
}
This solution is not very elegant but it works .The only other way I know would be to use the proper Win32 API's, which is tiresome.
Happy Coding
|
|
|
|
|
I used the above code in my application,
In both the condition like if the uploading file is open and close it is executing the catch statement,
try block is not executing if the uploading file is closed in user machine...
and also the code below the catch block is not executing...
only catch block is executing in this case,
So can u tell me how can i alter it to make it run successfully...
|
|
|
|
|
Sorry for that, but in your case this won't work as the OpenFileDialog Locks the file itself, so the IOException will always be caught. I created a function like this
private bool FileInUse(string fileName)
{
try
{
System.IO.FileStream fs = System.IO.File.OpenWrite(fileName);
fs.Close();
return true;
}
catch (IOException ex)
{
return false;
}
}
and then calling it like this
OpenFileDialog file1 = new OpenFileDialog();
if (file1.ShowDialog() == true)
{
if (!FileInUse(file1.FileName))
{
MessageBox.Show("Already Open");
}
else
{
using (Stream str = file1.OpenFile())
{
TextReader reader = new StreamReader(str);
reader.ReadToEnd();
textBox1.Text = file1.FileName;
textBox1.IsEnabled = false;
}
}
}
but this only works if the file is locked by the application that opens it (such as Word), otherwise if the file is open in an application that doesn't lock the file (such as NotePad), this always returns true.
|
|
|
|
|
Hello i have tried to get find some examples that draws behind the desktop icons and the ones i found did not do this in windows 7 atleast. so i thought i would have a go at overriding the onpaint or onrender but since im not the best yet! i can't seem to find the right way to do this. so far i managed to draw a circle behind by following this code
[DllImport("user32.dll")]
static extern IntPtr GetDesktopWindow();
[DllImport("user32.dll")]
static extern IntPtr GetDCEx(IntPtr hwnd, IntPtr hrgn, uint flags);
.......
IntPtr hdc = GetDCEx(GetDesktopWindow(), IntPtr.Zero, 1027);
using(Graphics g = Graphics.FromHdc(hdc))
{
g.FillEllipse(Brushes.Red, 0, 0, 400, 400);
}
then i tought what if i copied the e.graphics and put it into the newly created g and then tried to draw but i can't seem to copy the content of the painteventargs, is it even possible?
so i tought i ask the masters here. anyone know how to do something like this?
|
|
|
|
|
Probably impossible. You'd have to subclass the desktop window which I think is not allowed by the OS, then hook its WM_PAINT. That'd mean injecting yourself into explorer.exe (the correct instance). If you were able to accomplish that, it would be GDI/GDI+ only. I don't think you'd be able to render WPF content though.
|
|
|
|
|
oh, well i guess i have to find some other solution then. Thanks for the heads up
|
|
|
|