Archive for category Windows
Grabbing data from the registry on a remote machine using dot net and WMI
I recently had to write an app which, given a computer name, would grab their telephone extension from a registry key (For the purpose of the code example below, I just grab the CommonFilesDir key from the windows node. There’s a couple of ways you can achieve this- either using RegistryKey.OpenRemoteBaseKey which gave me a whole bunch of permissions issues, plus you need the remote registry and remote administration services active on the server/client OR you can use the Windows Management Instrumentation (WMI) service. I took this route, as it’s a service which is active by default on all of our machines on the domain, and it was easier to get the permissions right.
Before I paste the code, a GOTCHA to beware of, straight from the MSDN here;
The registry provider is hosted in LocalService—not the LocalSystem. Therefore, obtaining information remotely from the subtree HKEY_CURRENT_USER is not possible
ConnectionOptions options = new ConnectionOptions();
options.Impersonation = ImpersonationLevel.Impersonate;
options.EnablePrivileges = true;
options.Username = "<domain_admin_username>";
options.Password = "<domain_admin_password>";
// http://msdn.microsoft.com/en-us/library/system.management.managementscope.aspx
ManagementScope ms = new ManagementScope("\\\\<computer name>\\root\\default", options);
ms.Connect();
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa390788(v=vs.85).aspx
ManagementClass mc = new ManagementClass("stdRegProv");
mc.Scope = ms;
ManagementBaseObject inParams = mc.GetMethodParameters("GetStringValue");
// there are other methods for grabbing other reg types- see
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa393664(v=VS.85).aspx
inParams["hDefKey"] = RegHive.HKEY_LOCAL_MACHINE;
inParams["sSubKeyName"] = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion";
inParams["sValueName"] = "CommonFilesDir";
ManagementBaseObject outParams =
mc.InvokeMethod("GetStringValue", inParams, null);
if (outParams["ReturnValue"].ToString() == "0")
{
Console.WriteLine(outParams["sValue"]);
}
else
{
Console.WriteLine("Error " + outParams["ReturnValue"] + " please refer to http://msdn.microsoft.com/en-us/library/ms681382%28v=3Dvs.85%29.aspx");
}
Console.ReadLine();
This code requires this enum..
public enum RegHive : uint
{
HKEY_CLASSES_ROOT = 0x80000000,
HKEY_CURRENT_USER = 0x80000001,
HKEY_LOCAL_MACHINE = 0x80000002,
HKEY_USERS = 0x80000003,
HKEY_CURRENT_CONFIG = 0x80000005
}
If you receive a COM error back “The RPC server is unavailable”, make sure the target machine’s firewall isn’t blocking the call- this will open the port;
netsh firewall set service RemoteAdmin
Open Windows Firewall ports for SQL Server 2008
Posted by shawson in Batch Scripting, SQL Server, Windows on November 4, 2011
http://support.microsoft.com/kb/968872
As noted in the article, you can run this batch file;
@echo ========= SQL Server Ports =================== @echo Enabling SQLServer default instance port 1433 netsh firewall set portopening TCP 1433 "SQLServer" @echo Enabling Dedicated Admin Connection port 1434 netsh firewall set portopening TCP 1434 "SQL Admin Connection" @echo Enabling conventional SQL Server Service Broker port 4022 netsh firewall set portopening TCP 4022 "SQL Service Broker" @echo Enabling Transact-SQL Debugger/RPC port 135 netsh firewall set portopening TCP 135 "SQL Debugger/RPC" @echo ========= Analysis Services Ports ============== @echo Enabling SSAS Default Instance port 2383 netsh firewall set portopening TCP 2383 "Analysis Services" @echo Enabling SQL Server Browser Service port 2382 netsh firewall set portopening TCP 2382 "SQL Browser" @echo ========= Misc Applications ============== @echo Enabling HTTP port 80 netsh firewall set portopening TCP 80 "HTTP" @echo Enabling SSL port 443 netsh firewall set portopening TCP 443 "SSL" @echo Enabling port for SQL Server Browser Service's 'Browse' Button netsh firewall set portopening UDP 1434 "SQL Browser" @echo Allowing multicast broadcast response on UDP (Browser Service Enumerations OK) netsh firewall set multicastbroadcastresponse ENABLE
Command Line- create a folder named with todays date
Posted by shawson in Batch Scripting on August 23, 2011
mkdir %date:~-4,4%%date:~-7,2%%date:~0,2%
will produce a folder named like this; YYYYMMDD
Thanks to Mr Carmichael for this..
Automatic NAS Box shutdown – How to execute applications on Windows Shutdown (Part 2/2)
In Part 1 we looked at how to figure out what message was being sent from the web management page of my Netgear ReadyNAS Duo network storage box, and then how to replicate that to happy from a c# dot net console application. To finish this off, we now need some way of making that new console app run automatically when I shut down my Windows 7 PC.
I started in the Task Scheduler panel in Control Panel > Administrative Tools.
On the right hand panel you can then select “Create Task…”. From this dialogue you have a number of tabs along the top- the second one along, right after General is “Triggers” – switch to this and then hit the “New…” button which brings up a third window called “New Trigger”. From the drop down list entitled “Begin the task:” check the selected option from the default “On a schedule” to “On an event”. So you should now see something similar to this screen shot;
At this point I was kind of stumped- The other options in that “Begin the task:” list were things like “At log on”, “At startup”, “On work station lock” etc – there was no “On Shutdown”!! So I selected “On an event”. This gives you three new options in Settings – Log, Source and Event. From here it was down to taking an educated guess. I knew that shutting down Windows was likly to be logged as a “System” event, so in the first drop down I selected System.
What to choose in the Source drop down was not so clear- so to decide on an event source to use, I opened the Event Viewer, again from Control Panel > Administrative Tools. From the left hand panel, I opened the “Windows Logs” branch, then from within that selected “System”. These are arranged by time, so it’s just a matter of going back to when you turned your computer on today, then going back a couple more to see the last things your computer logged before turning off when you last used it.
In the end I opted for the event shown in the above screen shot- by reading the description I noticed it mentioned shutting down explorer.exe (a main component in Windows) because of the “power off of computer”, which I figured, with out knowing the in’s and out’s of what this really meant, sounded pretty promising. So from the same window I noted the Source “USER32″ and Event ID “1074″. Going back to the New Trigger window I found that USER32 did indeed appear in the list, so I selected that and entered 1074 as the event ID. This is pretty much everything for the trigger, so hit ok, then move on to the Actions tab, and click “New…”
From here it’s pretty easy- the action we want is to “Start a program” then just use the browser button to find the program you want to run. Click OK and return to the General tab.
This final step may not be required, but I did it anyway just to be sure- on the general tab, I changed the radio button at the end and selected “Run whether user is logged on or not”. I also changed the “Configure for:” drom down at the bottom to be “Windows 7, Windows Server 2008 R2″. And that’s it- Shut down your computer to give it a go. If you are following on from my previous post and you pointed the action dialogue to run the .exe produced from the last post, you should see your computer shut down and then a few seconds later the NAS box will power down.
Drop me a comment if I’ve missed any critical details!
Ninite Easy PC Setup – Silent Unattended Install Multiple Programs At Once
Nige at work pointed me over to an awesome site for creating a one stop setup for installing all your useful apps in one go after a format- just tick the apps you want and download the installer.
Ninite Easy PC Setup – Silent Unattended Install Multiple Programs At Once.
Command line to delete every file older than 30 days
Posted by shawson in Batch Scripting on February 19, 2010
I found a new command line directive i’d never heard of today, along with a brilliant example of it’s use- once you have changed your working directory, running this will remove any files or folders older than 30 days;
FORFILES /D -30 /C "CMD /C IF @isdir==FALSE (echo Deleting File @file) & (ATTRIB -H @file) & (DEL /F /Q @file) ELSE (echo Deleting Directory @file) & (ATTRIB -H @FILE) & (RD /S /Q @FILE)"
As an example, I’ve since used this to iterate over a bunch of folders, deleting any files over 30 days;
d:
for /f "delims=|" %%f in ('dir /b D:\_SQL_Backup\') DO (
cd \_SQL_Backup
cd %%f
FORFILES /D -14 /C "CMD /C IF @isdir==FALSE (echo Deleting File @file) & (ATTRIB -H @file) & (DEL /F /Q @file)"
)
Umbraco Installation – folder permissions setup
Posted by shawson in Batch Scripting, Umbraco on November 30, 2009
Just a real quick batch script i knocked up which sets the appropriate permissions to the various folders in the root of a fresh umbraco install- just drop this into a batch file, and run it from the root of your umbraco install;
REM 2009.10.22 SY - Set permissions- user/ folders from "Install Umbraco 4 on Windows Vista" guide icacls app_code /grant "Network Service":(OI)(CI)(F) icacls bin /grant "Network Service":(OI)(CI)(F) icacls config /grant "Network Service":(OI)(CI)(F) icacls css /grant "Network Service":(OI)(CI)(F) icacls data /grant "Network Service":(OI)(CI)(F) icacls masterpages /grant "Network Service":(OI)(CI)(F) icacls media /grant "Network Service":(OI)(CI)(F) icacls python /grant "Network Service":(OI)(CI)(F) icacls scripts /grant "Network Service":(OI)(CI)(F) icacls umbraco /grant "Network Service":(OI)(CI)(F) icacls usercontrols /grant "Network Service":(OI)(CI)(F) icacls xslt /grant "Network Service":(OI)(CI)(F) pause
Command line Batch File to Remove Direcories, using a Wild Card!
Posted by shawson in Batch Scripting, Command Line on October 28, 2009
We have a bunch of web services which log details of requests that come in, in folders named using the current date- in the format YYYY-MM-DDD-HH-MM-SS. I wanted to produce a simple cleanup batch file which we could run every month to bin all logs for transactions which happened 3 months ago- using the dos commands which exist on Windows Server 2003.
The dos “del” command allows you to delete using wild cards – so for example “dev 2009-07-*” would erase any files starting with “2009-07-”; However this doesn’t work with folders- so it fell to the rd (remove directory) command- but this doesn’t support wild cards (I’m assuming for safety- to stop you permanently erasing 100′s of folders and their contents accidently- remember there’s no recycle bin when you delete from the command line!).
To get around this I created a simple Batch file which accepted a wildcard as a parameter, then removes all those folders at the current level (it wont check recursivly). Just in case this is of use to anyone else, here’s the code;
REM - performs a remove directory, with wildcard matching - example ; rd-wildcard 2007-* dir %1 /b >loglist.txt setlocal enabledelayedexpansion for /f %%a in (./loglist.txt) do ( rd /s /q %%a ) del /q loglist.txt endlocal
Windows Vista, Visual Studio 2003/5 and Front Page Extensions!
We recently got new machines at work with Vista installed, allowing us to use IIS7, which has the added benefit of being able to run more than one site on the local IIS (unlike our previous IIS6 Win XP boxes)
When installing the various incarnations of visual studio to enable me to support some of our legacy app’s I came across a problem when installing Visual Studio 2003. One of the pre-requisites is front page extensions which are no longer shipped with Windows in Vista- the solution was a version of the extensions made by ready to run software which is actually linked to from the Official IIS Site (the article is named “FrontPage 2002 Server Extensions for IIS 7.0″ incase you have to use the site search, after another of microsoft’s random url switch around’s they’re so fond of) -you can grab the install from here : http://www.rtr.com/fpse/
Once you’ve run the installer, make sure you execute the following from the command line to activate them for your default website otherwise the .net installer still won’t recognise that you have them installed;
owsadm.exe –o install


