Thursday, June 27, 2013

Uninstall a KB

Open command prompt with admin privileges and execute the below command.

cmd.exe /c wusa.exe /uninstall /KB:2823324 /quiet /norestart

Your current security settings do not allow a file to be downloaded

Sometimes, you might see the below error while downloading a file.

Your current security settings do not allow this file to be downloaded
Below is the solution :

 Click on Custom Level

Select the “Enable” file download option

Friday, June 21, 2013

Extending PowerShell Commands : Modules

You can load additional commands in PowerShell via Modules.A module is really nothing more than a PowerShell script with a .psm1 file extension, although they can include binary code, typically delivered in a dll file.

Run below command to see modules exiting in your session :

PS > get-module

It is very possible you'll get nothing. But that simply means nothing is loaded in your session. We need to ask PowerShell to tell us what modules are available:

PS > get-module -ListAvailable

User modules are found in ...\Documents\WindowsPowerShell\Modules and system modules in $pshome\Modules. Some products may modify this variable. PowerShell gets this collection of objects by checking an environmental variable:

PS > $env:PSModulePath

When I want to use a module, I can import it. Consider i want to import the HyperV module, execute below command:

PS > Import-Module HyperV

If you have a module file in another folder outside of $env:PSModulePath, you can still import it if you specify the path:

PS > import-module S:\PSVirtualBox

To discover what the module can do, we can ask the Get-Command cmdlet:

PS > get-command -Module HyperV

CommandType   Name                 Definition
-----------   ----                 ----------
Alias         Add-NewVMHardDisk    Add-VMNewHardDisk
Function      Add-VMDisk           # .ExternalHelp MAML-VMDisk...
Function      Add-VMDrive          # .ExternalHelp MAML-VMDisk...
Function      Add-VMFloppyDisk     # .ExternalHelp MAML-VMDisk...
Function      Add-VMKVP            # .ExternalHelp MAML-VMConf...

I can use any of these commands as long as the module is loaded in my PowerShell session. Once I close my session the module is removed. If I want to always have this module available, I simply add the Import-Module command to my PowerShell profile. If you want to unload a module manually, you can do this:

PS C:\> Remove-Module HyperV

Thursday, June 20, 2013

Adding Domain user to local group on multiple computers

Want to add a user to a local group in multiple computers ? Try below steps.

Step 1. Copy Psexec.exe on your server. You can download it from here.

Step 2: Create Servers.txt in the same location where Psexex.exe resides and store the multiple computers IP.

Step 3 : Open Command prompt with Admin Privileges and change directory to where Psexec.exe resides.

Step 4: Execute below command now

Psexec.exe @servers.txt NET.exe LocalGroup Administrators domain\username /add 

Above example is for adding the user to Administrators group. If you need to add it to another group like Remote Desktop Users, enclose it within quotes.

Psexec.exe @servers.txt NET.exe LocalGroup “Remote Desktop Users” domain\username /add 

Wednesday, June 19, 2013

Checking Network Adapter Speed

Sometimes, just one line of PowerShell code gets you all the information you may have needed. There is a .NET type called NetworkInterface, for example, that lists all of your network adapters, their speed and status:
PS> [System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() | Select-Object -Property Description,Speed, OperationalStatus

Description                                Speed OperationalStatus
-----------                                ----- -----------------
Broadcom 802.11n Network Adapter        52000000                Up
VirtualBox Host-Only Ethernet Adapter  100000000                Up
Software Loopback Interface 1         1073741824                Up
Microsoft ISATAP Adapter                  100000              Down
Microsoft ISATAP Adapter #2               100000              Down
Teredo Tunneling Pseudo-Interface         100000              Down

Find Free Disk Space for a drive from a list of Servers

In order to get free disk space details for C: Drive of a list of Servers, execute below PS command.

Get-WmiObject -Class Win32_LogicalDisk -ComputerName (Get-Content C:\temp\Servers.txt) -Filter "DeviceId='C:'"|
Format-Table SystemName, @{Name="Free";Expression={[math]::round($($_.FreeSpace/1GB), 2)}},
@{Name="Total Size";Expression={[math]::round($($_.Size/1GB), 2)}} –auto

The list of Servers is stored under C:\temp\Servers.txt.
The output will give the Computername, Total Disk Space and Free Disk Space.

Insert timestamps into PowerShell outputs

For your PowerShell tasks, you can have a timestamp entered in series so you can determine how long a single step occurs or to use as a logging mechanism for your scripts. I find this handy in Graphical PowerShell when I’m testing scripts. To insert a timestamp, enter one of the following commands as a single line within your .ps1 file:
Output example
“$(Get-Date -format g) Start logging”
2/5/2008 9:15 PM
“$(Get-Date -format F) Start logging”
Tuesday, February 05, 2008 9:15:13 PM
“$(Get-Date -format o) Start logging”

There are many other formats for the Get-Date command, but these three options would generally suite most applications for timestamp purposes.

Counting no. of Files

If you need to know the number of files in a folder, there are different approaches with different advantages and disadvantages.

  The first one is using plain cmdlets and determines the number of files in the Windows folder:
Get-ChildItem -Path $env:windir -Force |
  Where-Object { $_.PSIsContainer -eq $false } |
Select-Object -ExpandProperty Count

           The second one does the same but uses .NET methods and is shorter and is about 20x as fast:

    And here's the commands to count the number of files recursively, including all subfolders:
Get-ChildItem -Path $env:windir -Force -Recurse -ErrorAction SilentlyContinue|
  Where-Object { $_.PSIsContainer -eq $false } |
-ExpandProperty Count

   Using .Net:


Again, the .NET approach is much faster, but it has one severe disadvantage. Whenever it comes across a file or folder it cannot access, the entire operation breaks. The cmdlets are smarter. Get-ChildItem and its parameter -ErrorAction can ignore errors and continue with the remaining files

Resolving URLs

Sometimes you may stumble across URLs like this one:

These are just "pointers" to the real web address. In PowerShell 3.0, the new cmdlet Invoke-WebRequest can resolve these URLs and return the real address that it points to:

(Invoke-WebRequest -Uri $URLRaw -MaximumRedirection 0 -ErrorActionIgnore).Headers.Location

Tuesday, June 18, 2013

PowerShell Web Access

PowerShell Web Access (PWA) is a fast, easy and secured method of accessing and managing the servers on your network from the outside. From any device, be it a phone, tablet or laptop, you can use ANY web browser to connect to PWA running on a web server and have a PowerShell console at your finger tips. If you have never seen it before, hold on to your socks because this will blow them off.

Requirements :

> Windows Server 2012
> IIS 8 and .Net 4.5 , PWA installation handles installation for both.

Installing Windows PowerShell Web Access :

Execute the below command in a PowerShell console
PS> Get-WindowsFeature *PowerShell*
You will see the feature Windows PowerShell Web Access listed.

PS> Install-WindowsFeature WindowsPowerShellWebAccess

Installing the PWA web application :

PWA is a web application that runs as part of the ‘Default Web Site’ in IIS.

PS> Get-Help *PSWA*
You will notice six cmdlets for PWA that will help in the installation, configuration and removal of PWA. The one we want to start with is Install-PswaWebApplication.

PS> Install-PswaWebApplication –UseTestCertificate
This cmdlet will perform several tasks for you so you don’t need to learn much about IIS. It will do below mentioned :

Create a new application pool for PWA
Create a new application – folder pswa off the default site – for PWA
Assign the application to the website files located in C:\Windows\web\PowerShellWebAccess\wwwroot
Assign a temporary non-trusted certificate for SSL to the site (this is only good for 90 days and should never be used in production).
Create a binding for HTTPS

Authorizing users for PWA usage :

You need to create an Authorization Rule (even several) that permits administrative users with the ability to use PWA and specify the servers they can manage. You will also need to specify a Remoting custom endpoint (if needed) that can restrict users to certain cmdlets and modules.

Below cmdlet specifies the specific user or group of users that have access to use PWA and the remote computers they are allowed to access:

PS> Add-PswaAuthorizationRule -UserName 'Company\Administrator' -ComputerName -ConfigurationName *

Testing PWA:

Open a web browser and type in the URL HTTPS://servername/pswa  or use below in PowerShell

PS> Start iexplore HTTPS://servername/pswa
You will first be warned of the non-trusted certificate, go ahead and continue. At the login screen, enter an authorized user name (including domain), the password and the remote server you added with the authorization rule.

Now you'll see a PowerShell Console in a Web browser.

Thursday, June 13, 2013

SQL SERVER – Get Database Backup History for a Single Database

Below Script can be used to retrieve backup history of a single database.

USE master
-- Get Backup History for required database
CAST(CAST(s.backup_size / 1000000 AS INT) AS VARCHAR(14)) + ' ' + 'MB' AS bkSize,
CAST(DATEDIFF(second, s.backup_start_date,
s.backup_finish_date) AS VARCHAR(4)) + ' ' + 'Seconds' TimeTaken,
CAST(s.first_lsn AS VARCHAR(50)) AS first_lsn,
CAST(s.last_lsn AS VARCHAR(50)) AS last_lsn,
CASE s.[type]
WHEN 'D' THEN 'Full'
WHEN 'I' THEN 'Differential'
WHEN 'L' THEN 'Transaction Log'
END AS BackupType,
FROM msdb.dbo.backupset s
INNER JOIN msdb.dbo.backupmediafamily m ON s.media_set_id = m.media_set_id
WHERE s.database_name = DB_NAME() -- Remove this line for all the database
ORDER BY backup_start_date DESC, backup_finish_date

Tuesday, June 4, 2013

Displaying a Custom Message in the Notification Area using Windows PowerShell

Use Windows PowerShell to display messages in the notification area. If you couldn’t, then we’d have had no reason to put together a script like this one:

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

$objNotifyIcon = New-Object System.Windows.Forms.NotifyIcon

$objNotifyIcon.Icon = "C:\Scripts\Forms\Folder.ico"
$objNotifyIcon.BalloonTipIcon = "Error"
$objNotifyIcon.BalloonTipText = "A file needed to complete the operation could not be found."
$objNotifyIcon.BalloonTipTitle = "File Not Found"

$objNotifyIcon.Visible = $True

We start out by using the following line of code to load an instance of the .NET Framework class System.Windows.Forms:

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

The [void] at the beginning on this line of code simply keeps status messages from appearing on the screen when we load the System.Windows.Form class.
After loading the System.Windows.Forms class we use the New-Object cmdlet to create an instance of the System.Windows.Forms.NotifyIcon class; as you might expect, this is the .NET class that actually lets us configure and display a notification in the notification area:

$objNotifyIcon = New-Object System.Windows.Forms.NotifyIcon

Following that we need to define several properties of our notice. In particular, we need to assign values to the following items:
This is the icon that appears in the notification area. The icon must be 16 pixels high by 16 pixels wide. If you have icon-editing software you can create your own icon; if not, try searching your computer (or the Internet) for .ICO files. Just make sure you specify the full path to the icon file when assigning a value to the Icon property: $objNotifyIcon.Icon = "C:\Scripts\Forms\Folder.ico".
This is the icon that appears inside your notice (see the illustration below). You can choose between the following operating system-supplied icons: InfoWarning; and Error. In our example, we’ve set the BalloonTipIcon to Error.
The actual message to be displayed. For this particular script we’ve set the BalloonTipText to “A file needed to complete the operation could not be found.”
The title of your notice. For our example, that’s File Not Found.

Or, to put it this all a little more visually:

After setting the Visible property to True ($True), all we have to do now is call the ShowBalloonTip method and display the notice:


A couple notes about the ShowBalloonTip method. For one thing, did you notice the parameter 10000 that we passed to ShowBalloonTip? Well, in theory, that indicates the number of milliseconds that we want our notice to stay on screen before automatically disappearing. Because there are 1000 milliseconds in every second, a value of 10000 means that, theoretically, we want the message to stay onscreen for 10 seconds, and then bid everyone a hasty goodbye.

That seems simple enough. So then why do we keep saying things like “in theory” and “theoretically”? That’s because there are some outside factors that come into play here. For example, the operating system imposes minimum and maximum values when it comes to displaying items in the notification area; typically a notice must remain onscreen for at least 10 seconds but no more than 30 seconds. What does that mean? Let’s put it this way: suppose you passed ShowBalloonTip the value 300000, thinking that would keep the notice displayed for 5 minutes (300,000 milliseconds). In reality, though, it’s highly unlikely that the notice will stay onscreen that long; instead, the operating system will probably dismiss it long before then. Likewise, suppose you set the parameter value to 1, thinking that you’ll show the notice for just 1 millisecond and then take it away. That’s not going to work, either: Windows will make sure that the notice is displayed for the minimum-allowed time before disposing of it.

On top of that, these times also depend on the amount of activity taking place on the computer. If the system appears to be idle then the countdown won’t begin until the computer actually does something. In that case, the notice could end up being displayed for hours.

Note. Of course, you can always dismiss a notice simply by clicking on it. Speaking of which, we should point out that any time a notification times-out the message will disappear, but the icon will remain in the notification area, at least until you pass the mouse through that area. However, if you dismiss a notice by clicking on it the icon will also disappear.

Regardless of how long it actually stays on screen, your notification will look something like this:

Another thing to keep in mind here is that your script will continue to run while the notice is displayed; the script won’t automatically pause and wait for the notice to disappear. That shouldn’t cause any problems; it’s just something you should be aware of.