Showing posts with label Windows Administration with Powershell. Show all posts
Showing posts with label Windows Administration with Powershell. Show all posts

Thursday, April 23, 2015

#58 : Find the disk volumes in host

WMI gives a lot of such important information which makes windows administration more manageable. Scripting becomes more and more robust than ever before. 

Powershell can be used to call WMI objects and we can get so much information out of it. 

CODE : 
get-wmiobject win32_logicaldisk | select DeviceId,Size, FreeSpace



You might get a result in proper tabular format. There are lot many scripts possible with this. 
1. Script to report low disk space
2. Script to display disk inventory in multiple hosts 

If you have trouble writing scripts mentioned above, just add your request in comment,  I will pick from there.

Thursday, April 16, 2015

#51 : How to check if Port if open or not?

This is fairly simply to test if certain host is able to connect to a port or not with Telnet. Some of the new SQL Server installation do not have Telnet installed. In those cases, we can use Powershell to test is the port.


I will use System.Net.Sockets.TcpClient class to accomplish it. Below is the simple statement to get the Port status.

$tcp = New-Object System.Net.Sockets.TcpClient

$tcp.connect(“HOST1″ , 1234 )


The above results as blank where connection is successful, otherwise, you get an error message.


Thursday, April 2, 2015

#50 : How to check with Powershell that URL is responsive or not?

You can write script in Powershell to check the status of certain URL (Uniform Resource Locator). In some cases, we may need to monitor if certain intranet application is working or not. Sometimes SQL Server Reporting services are required to be checked if URL is responsive.



To use it, you may call the function like below :

Check-URL "http://yourapplicationname.com"


That’s it! You are done and nothing more is required.

Thursday, January 22, 2015

#41 : View Process Commandline with Powershell

Process can be viewed easily in Powershell with Get-Process command. This command is useful, but it has some shortcomings -
1. It does not show the command-line and arguments passed to the command.
2. It does not show the Path of command.

Due to these shortcomings, I started looking for some option by which we can get the list of processes with complete details. The search completed and it came with WMI and Powershell combination. Below is the single line which can solve this problem.

Get-WmiObject Win32_process |   select  ParentProcessId, ProcessId, Name, Commandline  | ft

Based on the above, you can write a script which could kill processes by specific application, but be careful, killing a operating system process might shutdown the machine.

Happy scripting!!

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!!


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!!

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?

Tuesday, July 22, 2014

#19 : Find files more than Modified date of a File

Sometime, we come to a situation where we have to purge some files. The File-Purge has one more trick that it must be greater than LastWriteDate of a file.

Below code might help -

ls | where {$_.LastWriteTime -ge (ls | where { $_.name -eq "somd.flg" } ).LastWriteTime }

Wednesday, July 16, 2014

#18 : How to find Disk Fragmentation with Powershell

Hi Guys,

While doing a research on other topic, I came to know that there is a way to find the disk fragmentation details with Powershell. Below lines of code are sufficient to find disk fragmentation.

$drive = Get-WmiObject -Class Win32_Volume -Filter "DriveLetter = 'e:'"
$report = $drive.DefragAnalysis() > $null
$report.DefragAnalysis


Output: 
__GENUS : 1
__CLASS : Win32_DefragAnalysis
__SUPERCLASS :
__DYNASTY : Win32_DefragAnalysis
__RELPATH : Win32_DefragAnalysis
__PROPERTY_COUNT : 27
__DERIVATION : {}
__SERVER : DIVINE
__NAMESPACE : ROOT\CIMV2
__PATH : \\DIVINE\ROOT\CIMV2:Win32_DefragAnalysis
AverageFileSize : 72
AverageFragmentsPerFile : 1
AverageFreeSpacePerExtent : 8503984128
ClusterSize : 4096
ExcessFolderFragments : 1
FilePercentFragmentation : 0
FragmentedFolders : 1
FreeSpace : 42684555264
FreeSpacePercent : 81
FreeSpacePercentFragmentation : 45
LargestFreeSpaceExtent : 23402860544
MFTPercentInUse : 100
MFTRecordCount : 44159
PageFileSize : 0
TotalExcessFragments : 1
TotalFiles : 32684
TotalFolders : 5792
TotalFragmentedFiles : 1
TotalFreeSpaceExtents : 5
TotalMFTFragments : 2
TotalMFTSize : 45219840
TotalPageFileFragments : 0
TotalPercentFragmentation : 0
TotalUnmovableFiles : 10
UsedSpace : 9744240640
VolumeName :
VolumeSize : 52428795904

Line#2 might take some longer time depending on the disk size. So, if you are planning to run scan on all the servers of your environment - it might take longer time. But, the results are extremely accurate.

Happy scripting!!

Tuesday, July 15, 2014

#17 : How to execute command on Remote machine?

Powersell-remoting is one of the useful feature which might play important role in your scripting. Sometimes, it becomes important to roam over all machines and fetch some information. Such as finding the CPU Utilization in all machines or finding the Machine-Type of all servers of your environment. If you have a limited number of servers, the task can be done manually. But, if you have to run the same thing over all the machines - task would not be that easier.

I had this requirement long back and now I want to share my experiences with all of my audiences.

I will write a detailed article on it very soon.

#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...