Tuesday, December 30, 2014

#38 : Powershell script to Map Network drive

We often need to map network drives. Especially if you are writing a package which installs something from a shared drive. It becomes important to map drives and give a drive letter for the same.

Net share is the command which can be used to accomplish the same. Below is the Powershell version of the same -

Adding a Network Drive 
(New-Object -Com WScript.Network).MapNetworkDrive("x:" , "\\divine\d$")

That's it!
But this not the all about this. There might be further requirement to remove a network drive.


Listing the Network Drives
(New-Object -Com WScript.Network).EnumNetworkDrives()


Removing a Network Drive
(New-Object -Com WScript.Network).RemoveNetworkDrive("x:")

You can use EnumNetworkDrives() to find if particular share exists or not, then remove it. Anyways, there are several methods to do something, my job was just to give your tips not thesis.

Enjoy!!


Thursday, December 25, 2014

#37 : Download Files from Internet with Powershell

Powershell can be used to download a file from internet. This might help you matching some item from internet or you can create a download manager kind of software in Powershell.
Actually, you can do nearly everything which you can do in C# or any .NET based programming language because, .NET framework is common to C#, VB.NET and Powershell as well. Both Powershell or C# compile the code into MSIL (Microsoft Intermediate Language). But the only difference is Powershell is in form of script and C# will be a program. 
Powershell scripts can be compiled using C#, but again the compiled executable will require Powershell be installed on the machine. This cannot be called as standalone executable, but again I think "Can you run a C# code when .NET framework is not installed?". Anyways, lets not waste more time in thinking, below is the piece of code- 

(new-object System.Net.WebClient).Downloadfile("http://www.freeware995.com/bin/pdfedit.exe", "d:\pdfedit.exe")

Above is smallest inner line of a possible big code which will handle download of files from Internet. 

For sake of simplicity, I always prefer to give a one-liner. The reason is, when you want to know how to do something, your intention is basically to get something too small which can be further enhanced in your program. When I search, I look for a small code and I hope everyone does. There is no point is providing a complex code which you could not understand or incorporate in your code!

Enjoy scripting!!

Wednesday, December 17, 2014

#36 : How to find CPU Usage Percent with Powershell?

Hi All,

CPU-Utilization can be achieved with the command below -

Get-WmiObject win32_processor | select LoadPercentage | fl

Let's dissect the line and try to understand -


Posh (0016) > Get-WmiObject win32_processor


__GENUS                     : 2
__CLASS                     : Win32_Processor
__SUPERCLASS                : CIM_Processor
__DYNASTY                   : CIM_ManagedSystemElement
__RELPATH                   : Win32_Processor.DeviceID="CPU0"
__PROPERTY_COUNT            : 48
__DERIVATION                : {CIM_Processor, CIM_LogicalDevice, CIM_LogicalElement, CIM_ManagedSystemElement}
__SERVER                    : DIVINE
__NAMESPACE                 : root\cimv2
__PATH                      : \\DIVINE\root\cimv2:Win32_Processor.DeviceID="CPU0"
AddressWidth                : 32
Architecture                : 9
Availability                : 3
Caption                     : x64 Family 6 Model 23 Stepping 10
ConfigManagerErrorCode      :
ConfigManagerUserConfig     :
CpuStatus                   : 1
CreationClassName           : Win32_Processor
CurrentClockSpeed           : 1196
CurrentVoltage              : 16
DataWidth                   : 64
Description                 : x64 Family 6 Model 23 Stepping 10
DeviceID                    : CPU0
ErrorCleared                :
ErrorDescription            :
ExtClock                    : 200
Family                      : 185
InstallDate                 :
L2CacheSize                 : 1024
L2CacheSpeed                :
L3CacheSize                 : 0
L3CacheSpeed                : 0
LastErrorCode               :
Level                       : 6
LoadPercentage              : 1
Manufacturer                : GenuineIntel
MaxClockSpeed               : 2300
Name                        : Pentium(R) Dual-Core CPU       T4500  @ 2.30GHz
NumberOfCores               : 2
NumberOfLogicalProcessors   : 2
OtherFamilyDescription      :
PNPDeviceID                 :
PowerManagementCapabilities :
PowerManagementSupported    : False
ProcessorId                 : BFEBFBFF0001067A
ProcessorType               : 3
Revision                    : 5898
Role                        : CPU
SocketDesignation           : uPGA-478
Status                      : OK
StatusInfo                  : 3
Stepping                    :
SystemCreationClassName     : Win32_ComputerSystem
SystemName                  : DIVINE
UniqueId                    :
UpgradeMethod               : 185
Version                     :
VoltageCaps                 :




The result shows overall CPU-Utilization which can be matched with the CPU Usage in Task-Manager. WMI plays very important role in getting these valuable information. But this is also required that WMI service should be running on the machine where you are running these commands.



Happy scripting!!

Tuesday, December 9, 2014

#35 : How to know Windows Startup commands with Powershell?

Hi Guys,

Being Powershell developer, we always look for some good solution and simple solution. When I find something useful and simple, I share them with all of you.




While looking into WMI Explorer, I found a good stuff which could tell us the list of programs which run a windows start-up. Below is the command for the same -

Get-WmiObject -Class Win32_StartupCommand

Enjoy Scripting!

Wednesday, December 3, 2014

#34 : Find uptime of the host using Powershell

Sometimes we need to know the uptime of a host while troubleshooting. It plays lot more important role while troubleshooting.

We can use net stats srv command to get this information. If you check the output of this command, you will see a line which shows uptime is "Statistics since .. ". You can use this line and get desired result by doing some pipelining. The result should compare from current time and give result in number of days,hours, minutes and seconds.

You can see the article about "Difference between two dates" here for better understanding.

Let's try the command "net stats srv"

net stats srv 

Server Statistics for \\WIN-4SV8KNP9VNV


Statistics since 7/16/2017 1:11:09 AM


Sessions accepted                  0
Sessions timed-out                 0
Sessions errored-out               0

Kilobytes sent                     0
Kilobytes received                 0

Mean response time (msec)          0

System errors                      0
Permission violations              0
Password violations                0

Files accessed                     0
Communication devices accessed     0
Print jobs spooled                 0

Times buffers exhausted

  Big buffers                      0
  Request buffers                  0

The command completed successfully.



You may  notice that we can remove "Statistics since" and then uptime is there to be processed. We will use the same logic.


clear 
$uptime=net stats srv | where {$_ -match "since"} | foreach {$_.replace("Statistics since","") } | 
foreach { $($((Get-Date) - (Get-Date $_)).Days).tostring().padleft(3,"0").tostring() + ":" + 
 $($((Get-Date) - (Get-Date $_)).Hours).tostring().padleft(2,"0").tostring() + ":" + 
 $($((Get-Date) - (Get-Date $_)).Minutes).tostring().padleft(2,"0").tostring() + ":" + 
 $($((Get-Date) - (Get-Date $_)).Seconds).tostring().padleft(2,"0").tostring() 
 } | foreach { $_.replace(" ", "") } 

echo "Uptime of Host [$(hostname)]`t: $uptime (DD:HH:MM:SS)"


Output:
Uptime of Host [Divine] : 000:00:45:24 (DD:HH:MM:SS)

The above script can be modified to generate a report based on all hosts in your environment. But, I would like you to at least comment once. How long I would write without any comment?

#112: How to handle xml document in Powershell?

 In PowerShell, you can handle XML data using various cmdlets and methods provided by the .NET Framework. Here's a basic guide on how to...