prashant1987

Archive for the ‘PowerShell(Power) Scripting’ Category

HELLO’S,

Again after longtime I am writing here 🙂

Earlier today I was having bunch of Servers on which I was not sure if I have access to all of them. I wanted to know the server list on which my network ID is added to the Local Administrator Group. 🙂

I came up with below powershell script which help us to find out if the network ID has been added to the administrator list or not (Mainly for Remoting into the Server :))

$Servers = Get-Content C:\Servers.txt
Foreach($strComputer in $Servers)
{
try
{
$computer = [ADSI](”WinNT://” + $strComputer + “,computer”)
$Group = $computer.psbase.children.find(”Administrators”)
[string]$members = ($Group.psbase.invoke(”Members”) | %{$_.GetType().InvokeMember(”Adspath”, ‘GetProperty’, $null, $_, $null)}) -replace (‘WinNT://DOMAIN/’ + $server + ‘/’), ” -replace (‘WinNT://DOMAIN/’, ‘DOMAIN\’) -replace (‘WinNT://’, ”)
$m = $members.Replace(” “,”,”)
$k = $m.Replace(“/”,”\”)
[array]$l = $k -split “,”
if(($l | %{$_}) -eq “Contoso.com\User1”)
{
Write-Host “You have admin rights on $StrComputer”
}
Else
{
Write-Host “You don’t have admin rights on $StrComputer”
}
}
Catch
{
Write-Host “$Strcomputer has an exception”
}
}

The server list will go in C:\Servers.txt

Contoso.com\User1 — is the account name which you want to validate.

I hope this helps.

Thanks,

-Prashant Girennavar.

Advertisements

I am back here after long time  , and this time again I am up with one more interesting PowerShell script.

Script description :

  This Script will trigger installation of Microsoft WSUS patch updates on remote system. Script has multiple functions , each takes care of different tasks.

  The servers which needs to be patched remotely should be placed in servers.txt . Script will read the servers.txt and uses psexec.exe to initiate the patch installation.

 Update.vbs is a part of the script , and it has to be pushed to the remote computer where scripts triggers the installation of patches. PowerShell utlises this Update.vbs and installs the updates. Once updates are installed , this updates.vbs will be removed from the remote system.

Additionally , Script will prompt for restart option of remote system , ‘Y’ or ‘y’ will trigger the restart on remote machine , also it checks for server online (RDP Status) post reboot.

Below is the script 🙂

Update.Vbs

Set objSession = CreateObject(“Microsoft.Update.Session”)
Set AutoUpdate = CreateObject(“Microsoft.Update.AutoUpdate”)

WScript.Echo “Searching for updates…”

Set UpdateSearcher = objSession.CreateUpdateSearcher
Set SearchResult = UpdateSearcher.Search(” IsAssigned=1 and IsHidden=0 and IsInstalled=0 and Type=’Software'”)

Autoupdate.DetectNow()

If searchResult.Updates.Count = 0 Then
    WScript.Quit(0)
End If

Set updatesToDownload = CreateObject(“Microsoft.Update.UpdateColl”)
For i = 0 To SearchResult.Updates.Count-1
    Set update = SearchResult.Updates.Item(I)
    If Not update.EulaAccepted Then update.AcceptEula
    updatesToDownload.Add(update)
Next

WScript.Echo “Downloading the Updates”

Set downloader = objSession.CreateUpdateDownloader()
downloader.Updates = updatesToDownload
downloader.Download()

Set UpdatesToInstall = CreateObject(“Microsoft.Update.UpdateColl”)
For I = 0 To searchResult.Updates.Count-1
    set update = searchResult.Updates.Item(I)
    If update.IsDownloaded = true Then
        UpdatesToInstall.Add(update)
    End If
Next
WScript.Echo “Installating the Updates…..”
Set installer = objSession.CreateUpdateInstaller()
installer.Updates = updatesToInstall
installer.Install()

WScript.Quit(0)

PowerShell Script

# Name : Install-Patches on remote system
#Author : Prashant Girennavar.
#DateCreated : 4th Sept 2013.

# Function to create a Temp folder on remote machine if it does not exist
Function TempFolderCheck($Server)
{
 If(!(Test-Path \\$Server\c$\temp))
 {
   New-Item -type directory -path \\$Server\c$\Temp
 }
}

#Function to copy Update.vbs script on remote machine
Function BatchVBCopy($Server)
{
Write-host “VB Script is being copied on $Server”
Copy-Item -Path \\$SourceServer\C$\update.vbs -destination \\$Server\c$\Temp
}

#Function to trigger the patch installation on remote machine
Function InstallPatch($Server)
{
 try
 {
 .\psexec.exe -accepteula -s -i \\$Server cscript.exe C:\temp\update.vbs
 if($LASTEXITCODE -eq 0) #Check if PSEXEC executed successfully
 {
 Write-Host “$Server” Patched Successfully
 Remove-Item \\$Server\C$\Temp\Update.vbs #Remove the update.vbs from remote system
 $Reboot =  Read-Host “Do you wish to Reboot the system now? say Y to reboot / N to decline”
 if(($Reboot -eq “Y”)-or($Reboot -eq “y”))
 {
  Write-Host “Now Rebooting the $Server , Please wait ….”
  Restart-Computer -ComputerName $Server -Force #Restarting remote computer post patch installation
 }
}
 Else
 {
 Write-Host “$Server” Unable to patch the server please check
 }
 }
 Catch
 {
Write-Host “$Server” Encountered an exception
 }
 }

$Servers = Get-Content C:\Servers.txt # Get the server list which needs to be patched
Foreach($Server in $Servers)
{
TempFolderCheck($Server) #Call TempFolderCheck Function
BatchVBCopy($Server) #Call BatchVBCopy Function
InstallPatch($Server) #Call InstallPatch Function
}

Start-Sleep -Seconds 300 #Sleep for 5 mins

#Checking for server online status
Write-Host “Now Checking if all the servers are online post patch installation”
$Servers = Get-Content C:\Servers.txt
Foreach($Server in $Servers)
{
 $Connection = New-Object Net.Sockets.TcpClient # Add RDP Port .NET class
 $Connection.Connect($Server,’3389′) #Check for RDP Port 3389 status
 if ($Connection.Connected) #Check connection has been established
 {
  Write-Host “$Server is online after patching” -ForegroundColor Green
 }
 else
 {
 Write-Host ” $Server seems to have some problem , Please check it manually” -ForegroundColor Red
 }
}

$SourceServer = > where Update.VBS is stored

I Hope this script will help

Thanks,

_Prashant_

We are often Worried about , how much C:\ Drive Space is left on our Server or Client systems . Below script will help us to find out the C:\Drive space on Multiple servers and output will be save in CSV File with server name and its C:\Drive FreeSpace in GB

Get-WMIObject Win32_LogicalDisk -filter “DeviceId=’c:'” -computer (Get-Content c:\Computers.txt) | Select SystemName,@{Name=”freespace(GB)”;Expression={“{0:N1}” -f($_.freespace/1gb)}} | out-file C:\FreeSpace.csv –force

C:\Computers.txt contains list of servers/client systems on which you want to perform the Query

C:\FreeSpace.csv is output file where query result will be stored.

Hope this helps.

Thanks,

-Prashant Girenanvar.

NCPA.CPL How many people knows this ? If you are a system administrator , you defininately know this.

It’s indeed a tedious task to go to the NIC ——>Property and put the IP address , DNS Address and DNS Search Suffixes , Wins Address Manually . So , I though lets build a PowerShell script which will make administrator life easy . Below is the script

$IP = Read-Host “Please Enter the IP Address”
$Subnet = Read-host “Please Enter the SubnetMask”
$default = Read-host “Please Enter DefaultGateway”
$dns = “192.168.1.1”,”192.168.1.2″
$DNSsuffix =  “Contoso.com”,”Child.Contoso.com”
$a = Get-WmiObject -Class win32_networkadapterconfiguration -Filter “IPEnabled = true”
$a.EnableStatic($IP , $Subnet)
$a.setGateways($default)
$a.SetDNSServerSearchOrder($dns)
$a.SetWINSServer(“192.162.1.4″,”192.168.1.5”)
invoke-wmimethod -Class win32_networkadapterconfiguration -Name setDNSSuffixSearchOrder -ArgumentList @($DNSSuffixes),$null 

Script should be modified according to your environment. Below are the which one need to modify

$dns = “192.168.1.1”,”192.168.1.2″
$DNSsuffix =  “Contoso.com”,”Child.Contoso.com”
$a.SetWINSServer(“192.162.1.4″,”192.168.1.5”)

Read – host command line will ask you to provide IP address,SubnetMask,Defaultgateway in CMD Prompt

Hope this script will help to remove manual work

Regards,

_Prashant_

 

I had free time this evening , and I thought of using this time for PowerShell Scripting . So I came up with an IDEA to build a Powershell script which will query the list of servers and get the status of services(windows server) whose StartMode is set as Automatic.

As All of us know (Windows Administrators) , If the startmode of a service is set to automatic , that service has to be in “RUNNING” State ( Even If it screw’s your System 🙂 )

Some times this will not be the case , On Most of the instances if the server is patched and rebooted , some of the Automatic Services will not start.

To determine the servers and list of services , One can use Below PowerShell Code

Get-WmiObject -Class win32_Service -ComputerName (Get-Content C:\Names.txt) | ?{$_.StartMode -match “Auto*”} | Select-Object -Property * | %{ if($_.State -match “stopped”) {‘{0},{1},{2},{3}matic’ -f $_.SystemName,$_.DisplayName,$_.State,$_.StartMode | Out-File C:\AutoMaticServiceStatus.Csv -NoClobber -Encoding ascii -Append }}

Script will produce output C:\AutoMaticServiceStatus.csv in your C:\ Drive

Note – C:\Names.txt contains the Server Names against which we will run this powershell code.

Happy Scripting.

Thanks,

_Prashant_

I work in a enviorment , where we patch our servers on Monthly basis . Post patching it is important for us to know about the server status , How many servers got patched , How many servers are still have the downloaded patches , How many serveers have failed to install the patches Etc.

I came up with an IDEA to write a PowerShell Script to get an overall Overview about this.

Below is the script which one can use to Accomplish the above task ,

Note – Before Running the script make sure you have created a C:\Names.txt file (List of servers goes here) against which you will query WSUS server to get the details.

[void][reflection.assembly]::LoadWithPartialName(“Microsoft.UpdateServices.Administration”)
$global:wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::getUpdateServer(‘wsus ServerName Goes here’,$False,Port Number goes here of your WSUS)
$computerscope = New-Object Microsoft.UpdateServices.Administration.ComputerTargetScope
$updatescope = New-Object Microsoft.UpdateServices.Administration.UpdateScope
$s = Get-Content C:\Names.txt
$a = New-Object Microsoft.UpdateServices.Administration.ComputerTargetScope
$b = New-Object Microsoft.UpdateServices.Administration.UpdateScope
$c =  $wsus.getcomputertargets($a)
$id = @()
Foreach($Server in $s)
{
 $id += @($c | ? {$_.FulldomainName -like “$Server*”} | Select-Object -ExpandProperty ID)
}

$k = $wsus.GetSummariesPerComputerTarget($b,$a)
$k | Where-Object{$id -contains $_.ComputerTargetID} | ForEach {New-Object PSobject -Property @{
ComputerTarget = ($wsus.GetComputerTarget([guid]$_.ComputerTargetId)).FullDomainName
DownloadedCount = $_.DownloadedCount
FaliedCount = $_.FailedCount
}} | Export-Csv C:\PatchResult.csv -NoClobber -Force

Note –

$global:wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::getUpdateServer(‘wsus ServerName Goes here’,$False,Port Number goes here of your WSUS)

You need to put WSUSServerName , If you are using SSL then Please put $TRUE , and If you are using any other port otherthan 80 , then put the appropriate port ,. If you are using Default port please let it blank

script will produce C:\PatchResult.csv which contains all the required information.

Hope this will help when it comes to patching 🙂

Happy Scripting.

Regards,

_Prashant_

Reference – http://blogs.technet.com/b/heyscriptingguy/archive/2012/01/19/use-powershell-to-find-missing-updates-on-wsus-client-computers.aspx

I was participating in Powershell TechNet forum and someone asked question about how to add the ‘A’ Records and ‘PTR’ Records in DNS server . I thought it will be a good excercise for me , ( As I still have sleepless night when I think of Powershell :))

After working for long hours , I have built below script.

Note- One should have C:\DNS.CSV with columns as Hostname and IP address which needs to assinged. 

PowerShell Script

#Script to add DNS ‘A’ Records ‘PTR’ Records to DNS Servers
$dns = “DC” # Your DNS Server Name Goes here
$Zone = “AD.COM” # Your Forward Lookup Zone Name Goes here
$ReverseZone = “1.168.172.in-addr.arpa” # Your ReverseLookup Zone Name Goes Here
$a = import-csv C:\DNS.csv

#Preparing the C:\Reverse.csv from C:\DNS.CSV for Adding PTR Records
$b = $a | Select-Object -expand IP
$c = $b | %{$_.Split(“.”) | Select-Object -Index 3}
$d = $a | Select-Object -Expand Name
$e = $d | %{$_.Insert($_.length,”.ad.com”)}
for($i=0;$i -le ($e.Length);$i++)
{
(‘”{0}”,”{1}”‘ -f $c[$i],$e[$i]) | Out-File C:\Reverse.csv -Append -Encoding ascii
}

$header = “IP”,”Name”
$f = Import-Csv C:\Reverse.csv  -Header $header

#Adding ‘A’ Record to DNS Forward Lookup Zone
$a | %{dnscmd $dns /recordadd $Zone $($_.Name)A $($_.IP)}

#Adding ‘PTR’ Record to DNS Reverse Lookup Zone
$f | %{dnscmd $dns /recordadd $ReverseZone $($_.IP)PTR $($_.Name)}

Script will produce one more CSV File C:\Reverse.CSV which contains IP and FQDN Name Columns for PTR Record creation

Hope this script help AD Administrators 🙂

Regards,

_Prashant_