Showing posts with label Windows 2008. Show all posts
Showing posts with label Windows 2008. Show all posts

23 May 2017

Start Menu locations - Or add a simple Start Menu yourself without 3rd party tools

I keep forgetting the path to the Start Menu:
"C:\Program Data\Microsoft\Windows\Start Menu\Programs"

This is the same for Windows 7 up to Windows 10, and for Server 2012 to Server 2016.

But, wouldn't it be nice to have some sort of start menu without installing some malware/spyware infested tool? Then this quick fix is for you:

  • Display "Hidden items" on your C: Drive.
  • Open File Explorer and browse to your C: Drive. 
  • On the View tab, check the "Hidden items" checkbox.
  • Add a New Toolbar on your Taskbar.
  • Right-click on a blank area of your Taskbar and select Toolbars > New Toolbars.
  • Browse to the Start Menu\Programs folder.
  • In the New Toolbar dialog box, browse to the "C:\Program Data\Microsoft\Windows\Start Menu\Programs" folder. 
  • Click the "Select Folder" button.
  • Click the "Select Folder" button to add the new Toolbar to your Taskbar.

Here's what it looks like:

10 September 2014

Using Hyper-V with a Wireless Network Adapter

Out of the box Hyper-V does not support connecting virtual machines to wireless network adapters.  As a primarily server focused product this is a reasonable limitation - especially given that we need to do to get wireless network adapters to work with virtual machines.  But all is not lost - it is possible to setup an internal virtual network and utilize Internet Connection Sharing to get you up and going.
The first thing to do is to create a new internal virtual network switch:
  1. Open the Hyper-V Manager and select your server.
  2. Select Virtual Network Manager... from the action pane (on the right).
  3. Select New virtual network and choose to Add an Internal network.
  4. Give the new virtual network the name you want hit OK.
Now to setup Internet Connection Sharing:
  1. Open the Control Panel and open Network and Sharing Center.
  2. Select Manage network connections from the list on the left.
  3. Locate the icon for your wireless network adapter, right click on it and select Properties.
  4. Change to the Sharing tab.
  5. Check Allow other network users to connect through this computer's Internet connection.
  6. If you have multiple network adapters you will need to select the specific entry for the internal virtual network switch.
  7. Click OK.
You can now connect virtual machines to the internal virtual network and allow them to access the Internet through your wireless network adapter.

Source

Install Windows Server 2008 R2 on VHD bual boot on Windows 7

Great article on TechRepublic:

How to install Windows Server 2008 R2 with yper-V and Windows 7 on the same partition


By Colin Smith in Data Center, September 20, 2010
Blogger Colin Smith explains how to install Windows Server 2008 R2 with Hyper-V and Windows 7
on the same disk partition by booting from a VHD that contains the entire WS2K8R2 OS 
within a single, portable file.

Typically, dual-booting multiple operating systems requires repartitioning a disk, which isn't always
desirable, especially if you already have a multi-boot environment with Windows and Linux. What 
I am proposing is booting from a VHD - a virtual hard disk that contains the entire Windows Server
2008 R2 OS installation within a single, portable file hosted by your Windows 7 file system.What's
different about this post from the other boot-from-VHD posts out there? Admittedly, I did learn how
to create and install into VHD from some of the TechNet posts, but they focus on creating VHDs from within the WinPE console. Unfortunately, most of us work in Windows, not WinPE. 
So, what I have attempted here is to show you how to create the VHD from Windows 7 (or Windows Server 2008 R2), so that you can create VHDs for other purposes in addition to just an OS install. Additionally, I'll try to provide some other scenarios where you might want to consider using VHDs.

Why would you want to boot from a VHD?
There are several reasons:

  • There is no requirement to repartition your hard drive, which in itself tends to waste disk space since most partitions are typically over provisioned.
  • It simplifies image management for both VMs and physical systems as the same VHDs can be repurposed for both use cases.
  • You can move the VHD to a Hyper-V server or port it to another virtualization platform like ESX, Virtual Box, Xen , etc., that supports VHDs.
  • The VHD can be configured to be thin provisioned. This means that you can set the maximum size of the VHD and it will appear to the guest OS as a full partition, but in the host OS, it will only consume as much disk space as required to contain the entire guest OS. The VHD will grow in size up to the maximum as blocks are written to (allocate on write).
  • You can remove the entire OS by simply removing a single file and updating your boot menu.
  • It allows you to boot easily from an external device like an eSATA drive (USB or remote storage are not supported for Windows 7 or Windows Server 2008 R2 - Hyper-V Server is supported on USB/Flash )
  • You can easily back up the entire OS as a single file (like you would a VM).
  • You can have versioned OSs using a differencing disk to create a parent child relationship between VHDs. This can be very disk space friendly if you manage many images.
What you'll need:
  • A system capable of running Hyper-V (Intel VT or AMD-V enabled)
  • Windows 7 installed
  • 15 GB of free disk space
  • The ISO for Windows Server 2008 R2
Note: In the examples below, I am doing everything on drive C: and assigning drive letter Q: to the VHD but you can use any drive that Windows 7 has available.

Preparing the VHD
First we'll need to create a VHD on the Windows 7 system using the DISKPART command:
1.       From the Start->All Programs->Accessories right-click the Command Prompt and select "Run as Administrator" - DISKPART will launch and you will be put into the DISKPART CLI shell.
2.       Let's have a look at what volumes DISKPART can see. Type:
list vol↵
Take note of what you see.
3.       To create a minimal size VHD that can grow to a maximum size of 15000MB type:
create vdisk file=c:\win2k8r2.vhd maximum=15000 type=expandable↵
4.       To set the focus of DISKPART to the newly created VHD type:
select vdisk file=c:\win2k8r2.vhd↵
5.       To attach the virtual disk to the system type:
attach vdisk↵
6.       We will need a primary partition within the virtual disk to make the VHD bootable; type:
create partition primary↵
7.       Although the partition can be formatted as part of the Windows Server installation, I prefer to do it now. To format the partition with the NTFS file system, type:
format fs=ntfs quick label="NewVHD"↵
8.       We don't really need to assign a drive letter to the VHD at this point since during the install of Windows Server, it will get a different drive letter anyway, but it makes it more convenient to investigate the VHD from Windows 7. Assign the drive letter Q: to the new partition by typing:
assign letter=q: ↵
9.       Let's have a look at what volumes DISKPART can see now.  Type:
list vol↵
You should see the new volume available with a size of 14GB.
10.   To exit the DISKPART shell type:
exit↵
11.   To exit the command  shell type:
exit↵
12.   Use Windows Explorer to see what size the file c:\win2k8r2 that contains the VHD is. It should be around 80MB. It will grow from here as we add contents to the volume.
13.   For fun use right click Computer from the Start Menu and you should see drive Q: mounted. You can check the properties of drive Q: by right clicking it.

Installing Windows Server
Now we are ready to install Windows Server 2008 R2 onto the newly formatted partition within the VHD. I'll provide general instructions here, just highlighting the differences from a standard installation.
1.       Boot from the Windows Server 2008 R2 ISO. At the screen that prompts you to select a language press SHIFT+F10 to access the WinPE console.
2.       To launch the DISKPART CLI shell:
diskpart↵
3.       Let's have a look at what volumes DISKPART can see. Type:
list vol↵
4.       To set the focus of DISKPART to the previously created VHD, type:
select vdisk file=c:\win2k8r2.vhd↵
5.       To attach the virtual disk to the system, type:
attach vdisk↵
6.       Let's have a look at what volumes DISKPART can see. Type:
list vol↵
7.       To exit the DISKPART shell, type:
exit↵
8.       To exit the WinPE shell, type:
exit↵
9.       Return to the Windows Server 2008 R2 setup and select Custom (advanced) as the installation type, not Upgrade.
10.   When prompted for the installation location, select the newly formatted volume that has the label NewVHD.
11.   Perform the remainder of the installation as usual.
12.   When you reboot you will notice that you get a boot menu allowing you to select the OS of your choice. Select Windows Server 2008 R2.
13.   Turn on the Hyper-V role.

Now you have a dual boot Windows 7 and Windows Server 2008 R2 system that can also run the Hyper-V role even though it is not installed in its own partition of a physical disk.
At this point, you could migrate your Windows 7 installation to a VHD so that both of your operating systems are booting from VHDs. If you choose this route, the Disk2vhd tool might prove useful.

You could also use the VHD that you just installed Windows Server into as a Hyper-V (or ESX) virtual machine (you will need to recreate or modify the BCD store first).
By the way, the size of the VHD you created will probably be around 6 GB when viewed from the Windows 7 instance.

09 July 2014

Get system up time script and alternative ways

Save as a ps1 script, and run.

$computer = "computername"

$lastboottime = (Get-WmiObject -Class Win32_OperatingSystem -computername $computer).LastBootUpTime

$sysuptime = (Get-Date) – [System.Management.ManagementDateTimeconverter]::ToDateTime($lastboottime) 
  
Write-Host "$computer has been up for: " $sysuptime.days "days" $sysuptime.hours "hours" $sysuptime.minutes "minutes" $sysuptime.seconds "seconds" 

Outputs like:

PS D:\_DATA\Scripts> .\Uptime.ps1
computername has been up for:  71 days 4 hours 26 minutes 50 seconds

Alternatives:

1. Go to "Start" -> "Run".

2.  Write "CMD" and press on "Enter" key.

3. Write the command systeminfo | find "up time" and press on "Enter" key.

1. Go to "Start" -> "Run".

2.  Write "CMD" and press on "Enter" key.

3.  Write the command "net statistics server" and press on "Enter" key.


4.  The line that start with "Statistics since …" provides the time that the server was up from.

  •   The command "net stats srv" can be use instead.
Uptime.exe Tool Allows You to Estimate Server Availability with Windows NT 4.0 SP4 or Higher

Source

Alternate source

05 June 2014

Powershell 407 proxy authentication required

When trying to run Get-Software.ps1, you may receive an error message:

Do you want to Download PSExec ?
[Y] Yes  [N] No  [?] Help (default is "Y"): y
Exception calling "DownloadFile" with "2" argument(s): "The remote server retur
ned an error: (407) Proxy Authentication Required."
At D:\_DATA\Downloads\Hydrationkit\Build\Modules\Software.psm1:83 char:33
+                                 $WebClient.DownloadFile($Source, $Destination
)
+                                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : WebException

Run these commands to send your current credentials

$proxy = New-Object System.Net.WebClient

$Proxy.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials

After this the script runs fine:

Do you want to Download PSExec ?
[Y] Yes  [N] No  [?] Help (default is "Y"):

Do you want to Download SetupCA ?
[Y] Yes  [N] No  [?] Help (default is "Y"):

Do you want to Download Windows Assessment and Deployment Kit (ADK) for
Windows® 8 ?
[Y] Yes  [N] No  [?] Help (default is "Y"):


14 March 2014

What are "Schannel" errors and how to stop logging them

With certain Microsoft products, such as Exchange and Lync you see your evelogs filling up with "Schannel" errors; event id: 36888 The following fatal alert was generated: 51. The internal error state is 1306.

The event it self doesnt give out a lwhole lot of information but here is an explanation for it from technet:

When you enable Schannel event logging on a computer that is running Microsoft Windows NT Server 4.0, Microsoft Windows 2000 Server, Microsoft Windows XP Professional, Microsoft Windows Server 2003, Microsoft Windows Server 2008, or Microsoft Windows Server 2008 R2, detailed information from Schannel events can be written to the Event Viewer logs, in particular the System event log. This article describes how to enable and configure Schannel event logging. 


The internal error state is 1203 - From a support forum: "This event is seen on windows 2008 R2 running IIS. If a user tries to access a web site using HTTP but specifies an SSL port in the URL then this event is logged. This event is expected as the client is trying to use the wrong port or the wrong protocol to access the site
The error 1203 indicates invalid ClientHello from the client. This is by design and you can ignore this warning."

If your System eventlog is filling up with "Schannel" errors, and you want to stop this behavior, you can do the following.

Enable /disable logging

Warning Serious problems might occur if you modify the registry incorrectly by using Registry Editor or by using another method. These problems might require that you reinstall your operating system. Microsoft cannot guarantee that these problems can be solved. Modify the registry at your own risk.

Note This registry key is present already in Windows 2000 and XP Professional.
  1. Start Registry Editor. To do this, click Start, click Run, type regedt32, and then click OK.
  2. Locate the following key in the registry:
    HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\SCHANNEL
  3. On the Edit menu, click Add Value, and then add the following registry value:
    Value Name: EventLogging
    Data Type: REG_DWORD
    Note After you add this property, you must give it a value. See the table in the "Logging options" section to obtain the appropriate value for the kind of events that you want to log.
  4. Exit Registry Editor.
  5. Click Start, click Shut Down, click to select Restart, and then click OK to restart the computer. (Logging does not take effect until after you restart the computer).

Logging options

The default value for Schannel event logging is 0x0000 in Windows NT Server 4.0, which means that no Schannel events are logged. In Windows 2000 Server and Windows XP Professional, this value is set to 0x0001, which means that error messages are logged. Additionally, you can log multiple events by specifying the hexadecimal value that equates to the logging options that you want. For example, to log error messages (0x0001) and warnings (0x0002), set the value to 0x0003.
Collapse this tableExpand this table:

ValueDescription
0x0000                  Do not log
0x0001                  Log error messages
0x0002                  Log warnings
0x0004                  Log informational and success events

Source


23 January 2014

Disabled Accounts and ActiveSync Devices Continuing to Sync

Came across this article wich shed's some light on why users can keep on sending and receiving email when their password is expired or the whole useraccount is disabled.

This means that when a user leaves your company, disabeling the useraccount just doesn't cut it.

Disabled Accounts and ActiveSync Devices Continuing to Sync


Recently, an issue that has been around for some time started generating a lot of renewed interest.  The issue I'm referring to is regarding Exchange users still having access for several hours after their AD Account has been disabled.  This post is Part I of II, discussing why this happens and best practices to properly deal with/cut off access to users as quickly as possible relating to ActiveSync.  In Part II, I  will discuss this issue as it relates to Outlook and OWA and the best practices on how to deal with them
The main issue of concern is that if a user is terminated and just their AD account is disabled (which is a fairly standard process for many companies), that once their AD account is disabled it’s believed that the user is now stopped from being able to access anything using Windows Authentication, such as Exchange).  However, that may not necessarily be true…especially with ActiveSync.  If we’re talking about a terminated employee who was “walked out the door” and you want to IMMEDIATELY stop them from being able to send/receive emails via an ActiveSync device and all you've done is disable their AD account, they may still be able to sync for some time and send emails that you don't want sent.  This can then open a whole slew of headaches.

Why Does This Happen?

The ability for ActiveSync to continue to work even though the user's AD Account has been disabled is because of several reasons.  One of the main reasons is due to the way ActiveSync keeps a connection open to the server to watch for new messages.  That connection has already authenticated and has been validated…so while the AD count may be disabled, all Exchange knows is that the user HAD rights to the mailbox and is continuing to use that connection.  Eventually, the “life” of that authentication expires and the user has to re-authenticate (which is all done transparent to the user) and if the account was disabled, the re-authentication will fail and the user will no longer be able to sync.  ActiveSync devices with their long heartbeat intervals and token cache can still allow access up to 24 hours after an AD account has been disabled.  This is also related to caching done by IIS and Exchange, which I will talk about more in Part II.  But, in summary, just disabling a user's AD account will likely not stop them from accessing Exchange for at least a couple of hours if not more.

Best Practices to Follow Regarding Disabling User Access

  1. Before disabling the AD Account, you should do the following:
a. Trigger a remote wipe of the device - OPTIONAL
This may or may not be something you want to do depending on your company’s policies, if it’s a personal device, etc.  However, once the sync is stopped through other means the device cannot come in and get the Wipe Request, so this is one of the first things that should be done if your company deems it necessary.
b. In addition, implement a block of all their devices (if you didn't issue a remote wipe and/or their device doesn't support remote wipe, etc):
If using Exchange 2010/Office365:
Get information about the user and devices
Get-CASMailbox <user> | Select ActiveSyncAllowedDeviceIDs, ActiveSyncBlockedDeviceIDs
Get-ActiveSyncDeviceStatistics –Mailbox <user> | fl DeviceID
Block all Devices for a user
Set-CASMailbox -Identity <user> -ActiveSyncBlockedDeviceIDs "<DeviceID_1>,<DeviceID_2>"
If using Exchange 2007:
Get information about the user and devices
Get-CASMailbox <user> | Select ActiveSyncAllowedDeviceIDs
Get-ActiveSyncDeviceStatistics –Mailbox <user> | fl DeviceID
Block all Devices for a user
Set-CASMailbox -Identity <user> -ActiveSyncAllowedDeviceIDs "BLOCKED"
(Note: The use of the string “BLOCKED” is to enter a string that does NOT match any device they may be using as setting this value will ONLY allow a device with that Device ID string to sync [which no real device would have the Device ID of “BLOCKED”] and all others to NOT be allowed to sync)
c. Disable ActiveSync:
Set-CASMailbox -Identity <user> -ActiveSyncEnabled $false
d. Disable the mailbox (at least temporarily) - OPTIONAL
Note: It’s understood that some companies leave the mailboxes enabled to receive email so that OOF/automatic responses can be generated or so that no emails to the address are not blocked.  If this is the case, it’s recommended that you disable the mailbox for approximately 30m-1h and then enable again.  This will allow time for the change to go into effect and stop allowing ActiveSync to access.  This solution is in lieu of ActiveSync disabling as outlined above.
2. Disable the AD account.

Do note, the above changes are NOT instantaneous!  It can take around 5-10 minutes for the ActiveSync device blocking to go into effect, and that’s from the time that the change is replicated to all the DC/GCs used.  Obviously, if you make the changes against a DC/GC in another site and it has to replicate to the Internet-facing Exchange site(s) more time is needed.  The other settings can take up to 20 minutes to go into effect due to caching.
You may ask why we recommend using –ActiveSyncBlockedDeviceIDs AND –ActiveSyncEnabled?  It’s because the check for ActiveSyncBlockedDeviceIDs is checked almost continuously, since that part of Exchange is designed around the premise that devices are added or removed regularly.  However, ActiveSyncEnabled’s setting is cached for up to 20 minutes and then may only be rechecked if IIS Token Caching has expired.


Best Practices to Follow Regarding Disabling User Access

Here are the best practices related to Outlook and OWA:
  1. Before disabling the AD Account, you should do the following:
    1. Disable Web services for the mailbox:
For Exchange 2007:
Set-CASMailbox -Identity <user> -OwaEnabled $false
 For Exchange 2010:
Set-CASMailbox -Identity <user> -OwaEnabled $false
Set-CASMailbox -Identity <user> -EwsEnabled $false
Set-CASMailbox -Identity <user> -EwsEnabled $false
Set-CASMailbox -Identity <user> -EcpEnabled $false
  1. Disable MAPI services:
For Exchange 2007:
Set-CASMailbox -Identity <user> -MapiEnabled $false
Set-CASMailbox -Identity <user> -MapiBlockOutlookRpcHttp $true
For Exchange 2010:
Set-CASMailbox -Identity <user> -MapiEnabled $false
Set-CASMailbox -Identity <user> -MapiBlockOutlookRpcHttp $true
Set-CASMailbox -Identity <user> -EwsAllowMacOutlook $false
Set-CASMailbox -Identity <user> -EwsAllowOutlook $false
  1. Set Recipient Limits to 0
Set-Mailbox -Identity <user> -RecipientLimits 0
  1. Disable the mailbox (at least temporarily) - OPTIONAL
Note: It’s understood that some companies leave the mailboxes enabled to receive email so that OOF/automatic responses can be generated or so that no emails to the address are not blocked.  If this is the case, it’s recommended that you disable the mailbox for approximately 30m-1h and then enable again.  This will allow time for the change to go into effect and stop allowing clients to access.  This solution is in lieu of disabling as outlined above.
  1. Disable the AD account


Source:
Part 1
Part 2

18 November 2013

Windows 2008 Scheduled tasks result codes

To trouble shoot your scripts started by the task scheduler, and trying to figure out why it doesn't work:

  • 0 or 0x0: The operation completed successfully.
  • 1 or 0x1: Incorrect function called or unknown function called.
  • 2 or 0x2: File not found.
  • 10 or 0xa: The environment is incorrect.
  • 0x41300: Task is ready to run at its next scheduled time.
  • 0x41301: Task is currently running.
  • 0x41302: Task is disabled.
  • 0x41303: Task has not yet run.
  • 0x41304: There are no more runs scheduled for this task.
  • 0x41306: Task is terminated.
  • 0x8004130F: Credentials became corrupted HOTFIX available
  • 0x8004131F: An instance of this task is already running.
  • 0x800704DD: The service is not available (is 'Run only when an user is logged on' checked?)
  • 0xC000013A: The application terminated as a result of a CTRL+C.
  • 0xC06D007E: Unknown software exception.
  • 30 September 2013

    WSUS thorough cleanup

      

    1. Open the Windows Update Services MMC

    Wsus_console_big
      

    2. Select the All Updates View

    Set the display to show the Approval status of 'Any except Declined' with a Status of 'Any'. Click Refresh.
    All_updates_big
      

    3. Display the Supercedence Column

    Right-click the column headers and select Supercedence.
    Supercedence_column_big
      

    4. Sort by Supercedence

    Left-click on the Supercedece Column.
      

    5. Select and Decline the Superceded Updates

    The updates to be declined have one of two particular flowchart symbols for their updates pictured in the attached image. Select the correct updates and Decline them by either right-clicking the selected updates and clicking decline or by pressing the decline button in the action pane.
    Supercedence_icons_big
      

    6. Run the Server Cleanup Wizard

    Make sure you have all options selected in the wizard and let it run. It will delete the files from the declined updates.
    Wsus_cleanup_big
      

    7. OPTIONAL: Automatic Approval Options

    In the automatic approval options, under the advanced tab, there is an option to automatically approve update revisions for previously approved updates and subsequentially decline the now expired updates. I suggest you select them.
    Wsus_approval-adv_big

     

    04 June 2013

    Find and reset disconnected RDP Sessions

    We have a lot of servers. When I get disconnected, I may leave hanging sessions on those servers which I forget to properly close. Then, after I change the password for my admin account, I sometimes get locked out as a result of what I had open in the now disconnected session.

    Tracking this down is always annoying and time consuming.
    When users (including administrators) are terminated, you want to find and reset those sessions too. 

    ServerSessions.vbs is a script for admins to run to track down sessions on servers and optionally reset them. You can list sessions on all servers in a domain, and reset either all or just disconnected sessions

    The script in VBS:

    'ServerSessions.vbs
    'Lists and optionally resets a user's server sessions
    'Alan dot Kaplan at VA dot Gov. 
    '10/24/2011.  10/26 version fixed logging when list only

    Option Explicit    
    dim wshShell
    Set wshShell = WScript.CreateObject("WScript.Shell")
    Dim retval
    Const ADS_CHASE_REFERRALS_ALWAYS = &H20
    Dim oConn, oCmd, oRS
    Dim strADSPath, strADOQuery
    Dim strDomainCN
    Dim fso,logfile, appendout
    Dim strUser, strSessionID

    'Get the default ADsPath for the domain to search.
    Dim root: Set root = GetObject("
    LDAP://rootDSE")
    strADSPath = root.Get("defaultNamingContext")

    Const ForAppend = 8
    Set fso = CreateObject("Scripting.FileSystemObject")

    If (Not IsCScript()) Then   'If not CScript, re-run with cscript...
     dim quote
     quote=chr(34)

     WshShell.Run "CScript.exe " & quote & WScript.ScriptFullName & quote, 1, true
        WScript.Quit             '...and stop running as WScript
    End If

    If InStr(1,MyOS,"Server",1) = 0 Then
     MsgBox "You must run this from server OS",vbExclamation + vbOKOnly,"Error"
     'WScript.Quit
    End If

    retval = MsgBox("This script will identify and optionally logoff disconnected sessions for a user on all of the servers " & _
     "in AD within a domain. Do you want to continue?",vbYesNo + vbQuestion,"Get List of all Servers")
     If retval = vbNo Then WScript.Quit

    strADSPath = InputBox("Get server list from what domain","Domain",strADSPath)
     If strADSPath = "" Then WScript.Quit

    strUser = InputBox("Search for what username?","User Name",wshShell.ExpandEnvironmentStrings("%USERNAME%"))
    If strUser = "" Then WScript.Quit

    dim message
    message =  "Do you want to:" & VbCrLf & _
       "1) Get list only" & VbCrLf & _
       "2) Reset disconnected sessions" & VbCrLf & _
       "3) Reset all sessions for user" & VbCrLf & _
       "0) Quit" 

    Dim iActionType
    iActionType  = InputBox(message,"Choose Action",1)
    iActionType = CDbl(iActionType)
    If iActionType = 0 Then WScript.Quit


    GetServerList
    wshShell.Run "notepad.exe " & quote & logfile & quote

    ' =========== Functions and Subs ==========
    Sub GetServerList()
     '--- Set up the connection ---
     Set oConn = CreateObject("ADODB.Connection")
     Set oCmd = CReateObject("ADODB.Command")
     oConn.Provider = "ADsDSOObject"
     oConn.Open "ADs Provider"
     Set oCmd.ActiveConnection = oConn
     oCmd.Properties("Page Size") = 50
     ocmd.Properties("Chase referrals") = ADS_CHASE_REFERRALS_ALWAYS

     logfile = Replace(strADSPath,",","_")
     logfile = Replace(logfile,"DC=","")
     logfile = wshShell.ExpandEnvironmentStrings("%userprofile%") & "\desktop\" & strUser & " In " &  logfile & ".txt"

     If fso.FileExists(logfile) Then fso.DeleteFile logfile,True
     set AppendOut = fso.OpenTextFile(logfile, ForAppend, True)
     strDomainCN = DomainCN(strADSPath)

     '--- Build the query string ---
     strADOQuery = "<LDAP://" & strDomainCN & "/" & strADSPath & ">;" & "(&(OperatingSystem=*Server*)(objectClass=computer))" &  ";" & _
         "Name;subtree"
     oCmd.CommandText = strADOQuery

     '--- Execute the query for the object in the directory ---
     Set oRS = oCmd.Execute
     If oRS.EOF and oRS.Bof Then
       MsgBox  "No Servers AD entries found!",vbCritical + vbOKOnly,"Failed"
       appendout.WriteLine "Query Failed"
     Else
      While Not oRS.Eof
         SessionQuery oRS.Fields("Name")
        oRS.MoveNext
      Wend
     End If

     oRS.Close
     oConn.Close
    End Sub

    Sub SessionQuery (strServer)
     WScript.Echo "Checking " & strServer
     dim objEx, data
     Set objEx = WshShell.Exec("QWinsta /server:" & strServer)
     'one line at a time
     While Not (objEx.StdOut.AtEndOfStream)
      data = objEx.StdOut.ReadLine
      If InStr(1,data,strUser,1) Then
       strSessionID = GetSession(data)
       if iactionType = 1 then
        EchoAndLog strServer & ",found session for " & strServer
       Else
        Wscript.echo strServer & ",found session for " & strServer
       End if
       'always logoff
       If iActionType = 3 Then ResetSession strServer, strSessionID

       'Logoff disconnected
       If iActionType =2 And InStr(1,data,"disc",1) Then
        ResetSession strServer,strSessionID
       End If
      End If
     Wend
    End Sub

    Sub ResetSession(strServer, ID)
     Dim strCommand, oExec
     strCommand = "reset session " & id & " /server:"  & strServer
     Set oExec    = WshShell.Exec(strCommand)
     wscript.sleep 500

     'this is typically empty
     While Not (oExec.StdOut.AtEndOfStream)
      EchoAndLog oExec.StdOut.ReadLine
     Wend

     If oExec.ExitCode <> 0 Then
          EchoAndLog strServer & ",Problem resetting session " & ID & " on server " & strServer & ", Non-zero exit code, " & oExec.exitcode
     Else
      EchoAndLog strServer & ",Reset session " & ID & " on server " & strServer
     End If
    End Sub

    Function DomainCN(strPath)
     DomainCN = Replace(strPath,",",".")
     DomainCN= Replace(DomainCN,"DC=","")
    End Function

    Function MyOS()
     Dim oWMI,ColOS,ObjOS, OSver
     Set oWMI = GetObject("winmgmts:\\.\root\cimv2")
     Set ColOS = oWMI.ExecQuery("SELECT Caption, version FROM Win32_OperatingSystem")

     For Each ObjOS In ColOS
       MyOS = objOS.caption & Space(1) & objos.version
     Next
    End Function

    Function GetSession(text)
      text = strip(lcase(Text))
      Dim tArray, i

      tArray = Split(text,Space(1))
      i = 0
      While tArray(i) <> lCase(strUser)
       i = i +1
      Wend

      GetSession = tArray(i+1)
    End Function

    Function Strip(text)
     text = Replace(text,vbtab,Space(1))
     While InStr(text,Space(2)) > 0
      text = replace(text,Space(2),Space(1))
     Wend
     Strip = text
    End Function


    Sub EchoAndLog (message)
     'Echo output and write to log
     Wscript.Echo message
     AppendOut.WriteLine message
    End Sub 


    Function IsCScript()
        If (InStr(UCase(WScript.FullName), "CSCRIPT") <> 0) Then
            IsCScript = True
        Else
            IsCScript = False
        End If
    End Function


    Source

    30 May 2013

    Powershell script to check for stopped "Automatically started" services for multiple servers

    The powershell script below checks for services that are automatically started when the system starts.
    If a service is found stopped, the scripts starts the service and sends a notification email to an admin or a group.

    Multiple servers are supported, and services that stop automatically because they have no need to run al the time (software protection for instance) are filtered out.

    Modify the following to adjust for your environment:
    • The service name you want to exclude
    • The server array server names
    • The email receipients
    • The smtp server

    The script:

    #####################################################################
    # Author:  Edwin van Brenk                                                                                             #
    # date:  23-05-2013                                                                                                         #
    # Purpose: Check if auto start services for a number of                                                 #
    #                 servers are running, if not send a notification                                              #
    #                 email and start the service                                                                           #
    #####################################################################

    $Computers = "server1","server2","server3","server4"
    foreach ($Computer in $Computers)
     {
      #$exclusion = "clr_optimization"
      Write-Host "checking server: $computer"
      #Create an array of all services running
      $GetService = Get-WmiObject win32_service -ComputerName $Computer | where {($_.startmode -eq "Auto") -and ($_.state -ne "Running")}
      foreach ($service in $GetService)
       {
        if ($service.name -match "clr_optimization*")
         {
          Write-Host "`tService exclusion: " $service.name
         }
        elseif ($service.name -match "MMCSS")
         {
          Write-Host "`tService exclusion: " $service.name
         }
        elseif ($service.name -match "sppsvc")
         {
          Write-Host "`tService exclusion: " $Computer $service.name
         }
         elseif ($service.name -match "BMR Boot Service")
         {
          Write-Host "`tService exclusion: " $Computer $service.name
         }
         elseif ($service.name -match "NetBackup SAN Client Fibre Transport Service")
         {
          Write-Host "`tService exclusion: " $Computer $service.name
         }
         elseif ($service.name -match "SysmonLog")
         {
          Write-Host "`tService exclusion: " $Computer $service.name
         }
         elseif ($service.name -match "Mapsvc")
         {
          Write-Host "`tService exclusion: " $Computer $service.name
         }
         elseif ($service.name -match "NetBackup Vault Manager")
         {
          Write-Host "`tService exclusion: " $Computer $service.name
         }
         elseif ($service.name -match "NetBackup SAN Client Fibre Transport Service")
         {
          Write-Host "`tService exclusion: " $Computer $service.name
         }
         elseif ($service.name -match "NetBackup Key Management Service")
         {
          Write-Host "`tService exclusion: " $Computer $service.name
         }
         elseif ($service.name -match "RtcSrv")
         {
          Write-Host "`tService exclusion: " $Computer $service.name
         }
         elseif ($service.name -match "ShellHWDetection")
         {
          Write-Host "`tService exclusion: " $Computer $service.name
         }
        else
         {
          $servicename = $service.name
          Send-Mailmessage -to "
    admin1@domain.com","admin2@domain.com" -Subject "$servicename is stopped on $Computer" -from ServicesCheck@domain.com -Body "The $servicename service was found stopped on $computer. Check if the script started the service" -SmtpServer smtp.domain.lan
          Write-Host "`tStarting service " $service.name ".." -NoNewline
          $service.StartService()
          Write-Host "Done!" -BackgroundColor Green
         }
       }
     }

    12 February 2013

    Clean up Winsxs folder on Windows 2008 R2 SP1

    Starting from Service Pack 1, Windows 2008 R2 and Windows 7 finally has a built-in tool to reduce the size of the Windows Side-by-Side DLL repository and free up some GBs on your server storage. This tool is DISM.exe.

    The procedure is the following:

    Install Windows Service Pack 1 then ...

    Start and elevated command prompt (run 'CMD' as administrator) and ...

    Run the DISM command, which replaces the old VSP1CLN and COMPCLN we used on previous Windows versions:

    DISM.exe /online /Cleanup-Image /spsuperseded

    Wait 10 minutes before the task completes ( it ends with “Service Pack Cleanup operation completed. The operation completed successfully”)

    Normally you should have been able to reduce the Winsxs folder size by 1 or maybe 2 GBs, sometimes more. Saved space may vary a lot.

    Just know that after using DISM you will not be able to uninstall the Service Pack 1 anymore.

    Let's have a look at the used switches for DISM.exe:

    The /online switch tells DISM to work on the running OS installation
    The /spsuperseded option removes the backup files created during installation.


    Optionally you could use the /hidesp option which will remove SP1 (KB976932) from the “Installed Updates” section of Programs and Features, to ensure that users do not try to uninstall the Service Pack.