Syed Jahanzaib Personal Blog to Share Knowledge !

October 2, 2018

August 29, 2018

SystemState Backup failing under Windows Server 2016

Filed under: Microsoft Related — Tags: , , , , , — Syed Jahanzaib / Pinochio~:) @ 9:55 AM

We recently migrated our domain controller to Windows server 2016 edition. the DC is virtualized under vmware esxi 6.5 with vmware tools ver 10.1.x. I have schedule systemstate backup by using wbadmin command line tool. Example:

wbadmin start systemstatebackup -backuptarget:d: -quiet

After migration to 2016, I observed following error …

Error in backup of C:\windows\\systemroot\ during enumerate: Error [0x8007007b] The filename, directory name, or volume label syntax is incorrect.

After some searching , we found that this error is related to vmware tools version 10.1.x which sets incorrect path for some driver location.

To exactly find what file is causing, use following

  • Open command prompt [Run as Administrator] , type below and press ENTER.
DiskShadow /L writers.txt
  • The prompt will point to DISKSHADOW>
  • Now Type
list writers detailed

and press ENTER

  • After a while, this will list all of the writers and affected volumes. After completion, EXIT.

Open the writers.txt file in notepad or any text editor, then a search for windows\\ text , it should find the following:

File List: Path = c:\windows\\systemroot\system32\drivers, Filespec = vsock.sys

So the culprit was VSOCK.SYS To sort this we need to correct the path in the windows REGISTRY.

  • Run REGEDIT , then navigate to

HKLM\SYSTEM\CurrentControlSet\Services\vsock

  • Then change the ImagePath value string data from the incorrect
\systemroot\system32\DRIVERS\vsock.sys

to

System32\DRIVERS\vsock.sys

As showed in the image below …

BEFORE …

before

AFTER …

after path change

  • No need to reboot/log off. Simply run the backup again & this time you should see SUCCESSFUL report.

successfull backup after erg modifcation.JPG


 

Regard’s
Syed Jahanzaib

August 27, 2018

WSUS 2016 – Short Notes

Filed under: Microsoft Related — Tags: , , , , , , — Syed Jahanzaib / Pinochio~:) @ 10:58 AM

wsus-portfolio-1200x500

Recently we upgraded our infrastructure from windows 2003/2008 to 2016 servers. We have 2 DC’s on 2003/2008 and migrated them to 2016, afterwards when we added WSUS, it had many issues and it took almost 8-10 days to sort every thing. the reason why it took so many time that I tried my best NOT to re install the windows server again because this server was activated with valid license and we had limited license count on MS portal. Fixing messed up windows is far more time take taken process but yes you learn lot of new things in fixing old one, even if its not able to sort out.

I am adding few of the most annoying issues and there methods to sort them in this post. I will keep posting more.


1# Remove WSUS completely from 2016 Server

Sometimes when all sort of troubleshooting fails to restore WSUS, its better to install Fresh Windows, and add WSUS again. But in my case, this server was hosting WDS also & I really didn’t wanted to re install server OS (also to avoid licensing increment count on Microsoft Portal as we have limited license counts).

Following are steps to remove WSUS completely,

  1. Remove WSUS / IIS / Windows Internal Database (WID) Roles, (If you don’t remove the WID role and its files on a reinstall, it will re-attach to the same database)
  2. Reboot the server
  3. Now Remove following Folders
    C:\WSUS (or where ever the WSUSContent folder resides)
    C:\inetpub folder
    C:\Program Files\Update Services
    C:\Windows\WID
    C:\windows\system32\inetsrv  [Or rename this folder]
  4. Restart the server
  5. Re-add the WSUS And WID Roles (It will auto add the IIS role auto)
  6. Let it install, and then restart the Server again.
  7. Launch the WSUS console,

 


2# Post install Fatal Error: WsusPool does not exist

Please check the IIS, check Application Pools, check for WsusPool entry. If it’s not there, Add it manually as showed in the image below …

wsus pool does not exists.JPG

then run post-installation step again.


3# MMC console crashing

In one particular situation, when I added the WSUS role again, I was getting following error whenever I tried to open WSUS console …

wsus crashing.png

Since it was not a real production server, therefore I removed the WSUS (following all steps showed in Point # 1 of this guide, then executed

sfc /scannow

afterwards a reboot , & WSUS MMC worked well 🙂


4# Identify & approved required updates only

For good overview, read following

https://www.tecknowledgebase.com/43/how-to-identify-and-decline-superseded-updates-in-wsus/

.

August 20, 2018

Windows Server 2016 – Reference Notes

Filed under: Microsoft Related — Tags: , , — Syed Jahanzaib / Pinochio~:) @ 11:27 AM

.


1- Start Button Doesn’t Works !

When you click on Start button, it doesn’t popup.

  • Press Windows+RUN , and type
ms-settings:personalization-start

Uncheck following two options,

  1. Show more tiles
  2. Use start full screen

 

win2016 start button not working.JPG

That’s it !


2- Show icons on Desktop

Right click on Desktop

Select Personalize

Select Themes

On Right Window, Click on Desktop Icon Settings

allow desktop icons on desktop.JPG

If you receive following error

error on desktop icon setting.JPG

then you have to enable following setting in Domain controller default group policy policy, reboot client to take changes immediately or gpupdate /force

policy for runddl32 exec error.JPG


 

July 16, 2018

Windows 10 Pro Build 1803 unable to join 2008/2003 Domain

Filed under: Microsoft Related — Tags: , — Syed Jahanzaib / Pinochio~:) @ 4:22 PM

win10 pro 1803.JPG


Scenario:

Active Directory Domain Controller

  • Domain Controller 1 = Windows 2008 R2
  • Domain Controller 2 = Windows 2003 R2
  • Domain Name = MYCOMPANY (Single Label Domain)
  • Functional Level > Windows Server 2003

Clients:

  • Mix of Windows 7 Pro / Windows 10 / Windows 2008

Problem #1

Recently we downloaded latest build of Windows 10 Pro Edition 1803. After its deployment on client, we tried to join one test PC to the company domain but failed to do so with below error …

win10 error 1803 error.JPG

 

Ac active directory domain controller (AD DC) for the domain "MYCOMPANY" could not be contacted.
Ensure that the domain name is typed correctly.

Previous version of windows 10 were already joined with the domain properly. but only this new build version 1803 is not able to join domain. I can ping domain controller names via effected clients. nslookup working ok.


Workaround:

Proper Solution:

  • If you are using Single Label Domain , then rename it with full FQDN naming. joinging with full FQDN will sort the issue.
  • Upgrade 2003 DC’s to 2008 at least and raise functional level to Windows 2008,
    Or better to move to Windows 2012/2016 DC.

but if above suggestions are not doable like in my case, then follow below workaround as a temporary workaround,

Edit registry and add AllowSingleLabelDnsDomain . Full details as below ,

Open REGEDIT 

Find this subkey

  • HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Netlogon\Parameters

Locate this > AllowSingleLabelDnsDomain.

If the key AllowSingleLabelDnsDomain does not exist, then create , New  DWORD (32 bit)

  • DWORD Key Name: AllowSingleLabelDnsDomain

Double click AllowSingleLabelDnsDomain

Set the Value to 1

  • AllowSingleLabelDnsDomain > 1

Exit regedit

Reboot Windows 10

Now try to join the AD domain.

Hopefully it will work, At least in my case it did 🙂


Problem #2

SMBv1 is not installed by default in Windows 10 Fall Creators Update and Windows Server, version 1709 and later versions

Open CMD (with Admin Rights)

Open Powershell by powershell command

& issue following command

Enable-WindowsOptionalFeature -Online -FeatureName SMB1Protocol
Detect: Get-WindowsOptionalFeature –Online –FeatureName SMB1Protocol
Disable: Disable-WindowsOptionalFeature -Online -FeatureName SMB1Protocol
Enable: Enable-WindowsOptionalFeature -Online -FeatureName SMB1Protocol

More information here,

https://support.microsoft.com/en-us/help/2696547/how-to-detect-enable-and-disable-smbv1-smbv2-and-smbv3-in-windows-and


Regard’s
Syed Jahanzaib

June 19, 2018

Microsoft Products Short Notes – Personnel References

Filed under: Microsoft Related — Tags: , , , , , , , , — Syed Jahanzaib / Pinochio~:) @ 9:25 AM

This post contains shot notes / Tips for personnel references, These are common task that we perform on daily basis in out IT slavery !
Reagrd’s
Syed Jahanzaib


Powershell PSTerminalServices module

This module helped to see who is logged on remote pc via RDP with client ip/name

First download the module from here ….

then import it in powershell. make sure to run powershell RUN as admin.

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
Get-Module -Name PSTerminalServices -ListAvailable
Import-Module PSTerminalServices
Get-Command -Module PSTerminalServices

# Gets all Active sessions from remote computer ‘comp1′, made from IP addresses that starts with ’10’.

Get-TSSession -ComputerName ZAIBPC

OR

Get-TSSession -ComputerName comp1 -Filter {$_.ClientIPAddress -like '10*' -AND $_.ConnectionState -eq 'Active'}

MORE COMMANDS

# Logs off all the active sessions from remote computer 'comp1', no confirmations
Get-TSSession -ComputerName comp1 -State Active | Stop-TSSession –Force

# Displays a message box inside all active sessions of computer name 'comp1'."}
PS > $Message = "Importnat`n, the server is going down for maintenance in 10 minutes. Please save your work and logoff."
PS > Get-TSSession -State Active -ComputerName comp1 | Send-TSMessage -Message $Message

# Gets all processes connected to session id 0 from remote computer 'comp1'.
PS>Get-TSSession -ID 0 -ComputerName comp1 | Get-TSProcess

 


Check motherboard version

wmic baseboard get product,Manufacturer,version,serialnumber

PSTOOLS Related

.

Adding Local Account in remote workstation with PSTOOLS

If you are domain admin, and wanted to add local account in remote client workstation, then use pstools’s psexec 

psexec.exe \\target-pc net user /add USERNAME  USERPASSWORD
psexec.exe \\target-pc net net localgroup administrators USERNAME /add

# PSLOGGEDON COMMANDS
To check which user is logged on remote pc,

psloggedon \\remotepc

# PSEXEC COMMANDS

– To execute any command on remote pc like

psexec \\remtotepc ipconfig

– To open COMMAND prompt of remote user

psexec \\remotepc cmd

-Interacting with the Logged On User on the Remote PC

psexec \\remotepc -d -i notepad

# PSINFO COMMANDS
Getting general info with disk info as well

psinfo -d \\remotepc

# PSLIST COMMANDS

pslist \\remotepc

# PSKILL COMMANDS
– Kill remote pc program

pskill \\remotepc notepad

to query time

net time \\REMOTEPC

To change time on remote pc with domain server agpinf05

C:\pstools>PsExec.exe \\REMOTEPC -u DOMAIN\ADMIN -p PASS cmd "/c net time \\DC /set /y"

 


Batch file to change setting of network adapters to obtain IP from DHCP

Make sure to change adapter names to match your’s …

@echo off
echo Setting IP Address to AUTO DHCP [Office DHCP Server by syed.jahanzaib]...
netsh interface ip set address name="Local Area Connection" source=dhcp
netsh interface ip set dns "Local Area Connection" source=dhcp
netsh interface ip set address name="Wireless Network Connection" source=dhcp
netsh interface ip set dns "Wireless Network Connection" source=dhcp
echo Done....

Command to change IP via CMD

netsh interface ip set address name=”Local Area Connection” static 192.168.0.1 255.255.255.0 192.168.0.254
netsh interface ip set dns name=”Local Area Connection” static 192.168.0.250
netsh interface ip add dns name=”Local Area Connection” 8.8.8.8 index=2

Check Remote PC OS version & other details by CMD

systeminfo /s \\REMOTEPCNAME
# OR
systeminfo /s \\REMOTEPCNAME|findstr /i "host OS "

Result:

C:\>systeminfo /s \\syed_jahanzaib

Host Name: SYED_JAHANZAIB
OS Name: Microsoft Windows 7 Professional
OS Version: 6.1.7601 Service Pack 1 Build 7601
OS Manufacturer: Microsoft Corporation
OS Configuration: Member Workstation
OS Build Type: Multiprocessor Free
Registered Owner: Syed Jahanzaib
Registered Organization:
Product ID: xxxxxx-005-xxxx-xxxx
Original Install Date: 4/11/2017, 1:14:44 PM
System Boot Time: 6/19/2018, 7:44:47 AM
System Manufacturer: INTEL_
System Model: DH77KC__
System Type: x64-based PC
Processor(s): 1 Processor(s) Installed.
[01]: Intel64 Family 6 Model 58 Stepping 9 GenuineIntel ~3392 Mhz
BIOS Version: Intel Corp. KCH7710H.86A.0069.2012.0224.1825, 2/24/20
12
Windows Directory: C:\Windows
System Directory: C:\Windows\system32
Boot Device: \Device\HarddiskVolume1
System Locale: en-us;English (United States)
Input Locale: en-us;English (United States)
Time Zone: (UTC+05:00) Islamabad, Karachi
Total Physical Memory: 8,090 MB
Available Physical Memory: 2,450 MB
Virtual Memory: Max Size: 16,178 MB
Virtual Memory: Available: 10,455 MB
Virtual Memory: In Use: 5,723 MB
Page File Location(s): C:\pagefile.sys
Domain: DOMAIN1
Logon Server: \\DOMAIN_DC
Hotfix(s): 187 Hotfix(s) Installed.
...........................
Network Card(s): 3 NIC(s) Installed.
[01]: Intel(R) 82579V Gigabit Network Connection
Connection Name: DOMAIN - LAN
DHCP Enabled: No
IP address(es)
[01]: 192.168.100.100
[02]: 192.168.50.10
[03]: 192.168.8.23
[02]: VMware Virtual Ethernet Adapter for VMnet1
Connection Name: VMware Network Adapter VMnet1
DHCP Enabled: No
IP address(es)
[01]: 169.254.97.149
[02]: fe80::ad90:fdcb:3f81:6195
[03]: VMware Virtual Ethernet Adapter for VMnet8
Connection Name: VMware Network Adapter VMnet8
DHCP Enabled: No
IP address(es)
[01]: 169.254.80.235
[02]: fe80::5598:be9:b61d:50eb

C:\>

DCHP Related ! [Tested with W2008]

DHCP is running on windows 2008 server, IP is 192.168.0.1


#DCHP BACKUP
netsh dhcp server 192.168.0.1 dump > c:\dhcpoutput.txt all

#DHCP DELETE OLD SCOPE
netsh dhcp server delete scope 192.168.0.0 dhcpfullforce

#DHCP IMPORT
[Disable DHCP Service before import]
netsh dhcp server import c:\tools\dhcpoutput all

#DHCP DISABLE
netsh dhcp server 192.168.0.1 scope 192.168.0.0 set state 0

Disable Internet Explorer Proxy via CMD

REG ADD "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyEnable /t REG_DWORD /d 0 /f

Clear cache in windows

ipconfig /flushdns
net stop dnscache
net start dnscache

Event ID

https://www.ultimatewindowssecurity.com/securitylog/encyclopedia/default.aspx?i=j


Excel 2010 showing Blank Sheet

in Excel 2010 , When you open any excel sheet,( any particular, either yours or sent to you by some one else , it appears blank sheet

This may also occur if your computer’s screen resolution is higher than that of the person who last saved the workbook.

In Excel 2010, go to the View tab.

Select the ‘Arrange All’ button, then choose to Cascade.

OR

Excel 2010
opening blank sheets

ctrl+shift and open file
or its related with MACRO, run macro


Display Mother board model via CMD

- To find Board number of local pc
wmic baseboard get product,Manufacturer,version,serialnumber

- To find Board number of remote pc
wmic /node:"remotepc" baseboard get product,Manufacturer,version,serialnumber

- To find remote pc Architechture liek 32bit or 64bit
wmic /node:"remotepc" os get osarchitecture

Adding Static Routes in Windows via CMD

Adding route for single host

route -p ADD 10.1.1.12 MASK 255.255.255.255 101.11.11.4 METRIC 1 IF 11

Notes:

To open a command prompt, click Start, point to All programs, point to Accessories, and then click Command prompt.

To make a static route persistent, you can either enter route add commands in a batch file that is run during system startup or use the -p option when adding routes.

Routes added by using the -p option are stored in the registry under the following key:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip \Parameters\PersistentRoutes

Windows 7 Temporary profile Issue:

http://www.sysprobs.com/fix-temporary-profile-windows-7


There is no script engine for file extension .vbs

When we upgraded from win7 to windows 10/2012, our domain welcome logon script stopped working, with above error, to sort it we copied welcome vb script to domain logon folder and used this …

cscript //e:vbscript c:\path\to\script.vbs

Convert bootable USB in ISO file

The instructions for USB to .iso are as follows (for a Windows 7 installation for example):

  1. Install ImgBurn. You can even get a portable version of it, just search for it.
  2. Plug the bootable USB into the computer
  3. Start ImgBurn.
  4. Click on the “Create image file from files / folders” button on the home menu.
  5. In “Sources” browse to the USB drive.
  6. In “Destination” choose where to save the final .iso image.
  7. Go to the “Advanced” tab on the right and then “Bootable Disk”.
  8. Check the box “Make Bootable Image” and then, in the “Boot image” box browse to file “etfsboot.com” that is in the USB stick found in the folder “boot”.
  9. In the field “Developer ID” put “Microsoft Corporation” and enter “07C0” in the “Load Segment” field.
  10. Enter ‘4’ in the ‘Sectors To Load’ field if your etfsboot.com file is 2K is size, enter ‘8’ if it’s 4K. In other words, x = size of etfsboot.com in bytes / 512.
  11. Click “Build” and you’re done!

Credits: https://mindthebandgap.wordpress.com/2013/03/13/how-to-convert-bootable-usb-into-an-iso-file/


Reboot Remote Workstation from Domain Admin PC

shutdown /r /t 60 /m \\REMOTE-PC /c "YOU PC WILL REBOOT AFTER 1 MINUTE..."

.NET Framework 3.5 error code 0x800F081F on Windows 10.

net error.png

To solve it, use following.

Dism /online /enable-feature /featurename:NetFx3 /All /Source:D:\sources\sxs /LimitAccess

In above command make sure to change the path D:\sources\sxs to your windows 10 dvd / usb location. Basically You have to provide the Windows installation DVD/USB path so that it can copy the required files for .net


Regard’s
Syed Jahanzaib

June 13, 2018

Skype for business WEBAPP stops on Loading

Filed under: Microsoft Related — Tags: , , — Syed Jahanzaib / Pinochio~:) @ 1:31 PM

Skype for business webapp is a quick method to join meetings invitation sent by remote parties. Today when one of our user (with Windows 7 & IE8) tried to join the meeting  using Google Browser (latest version) (with S4B webapp plugin installed) , the window stuck at Loading … as showed in the image below …

SKYPE FOR BUSINESS STUCK ON LOADING ERROR

After some R&D, it found that if you have IE 8 or below, you must upgrade to new version.

After we upgraded IE from 8 to 11 , the S4B webapp worked smoothly.

skype working ok afger IExplorer 11 updates.png

April 6, 2018

Veeam B&R 9.5 Update 3 Error: This Veeam Backup & Replication installation can not be updated automatically

Filed under: Microsoft Related, VMware Related — Tags: — Syed Jahanzaib / Pinochio~:) @ 2:32 PM

Recently when we tried to apply veeam B&R update 3 , we encountered following error …

This Veeam Backup & Replication installation can not be updated automatically. Please contact Veeam customer support for assistance with manual update.

vbr95up3 error.JPG

After some investigation it found that it can occur dueto either you are running trial or if you have problem with the license files. Therefore as a workaround to enforce Update Pack 3 which was required dueto requirement of addition of Esxi 6.5 Vcenter, I followed below steps …

Rename following files

VeeamLicense.dll > to > VeeamLicense.dll.old
[ available in C:\Program Files\Common Files\Veeam\ ]

veComLic.dll > to > veComLic.dll
[ available in C:\Program Files\Common Files\Veeam\Backup And Replication ]

Now run the Update Pack 3 and it will run smoothly.

v95up3

Once Done, execute Veeam , It may show license is invalid, just ignore and move forward, it may ask you to update component, just do it, when done, close the veeam.

Now go back to

  • C:\Program Files\Common Files\Veeam
  • C:\Program Files\Common Files\Veeam\Backup And Replication

You may see new VeeamLicense.dll veComLic.dll files, just remove them, and rename the previous .old files to original names.

Now start Veeam again, & hopefully this time all will be fine.

 

v br 95 up3 final.JPG

March 8, 2017

MS Project 2016 has stopped working on assign resources

Filed under: Microsoft Related — Tags: , , — Syed Jahanzaib / Pinochio~:) @ 9:49 AM

microsoft-project-2016-license-key-e1469786312356

Recently we purchased Microsoft Project 2016 licenses for our users. In terms of Functionality – All seems to be working fine except assigning resources

Whenever user tried to assign resources using option `Assign Resources` , project crashed/stopped working with below error …

ms_project_2017_stopped_wroking

 

After little R&D, we found that this is a standard bug in MS Project 2016 and it was fixed with Patch released on February 9, 2016

February 9, 2016, update for Project 2016 (KB3114714)

After updating patch, all went fine.


Advise of the day ! (Golden Rule)

Although we have WSUS (Windows Update Servers) in our organization which regularly update the clients windows , but general patches for MS OFFICE was not selected in the checklist, & that’s the main reason why we had to face this issue. Always keep your Windows and other softwares UP TO DATE. It will keep you away from UNWANTED guests 😉 You know what I mean 🙂

Regard’s
Syed Jahanzaib

February 21, 2017

PowerShell Reference [Continued Post]

Filed under: Microsoft Related — Tags: , , , , — Syed Jahanzaib / Pinochio~:) @ 8:34 AM

pwoershell-logo

coffe code.PNG

Following is reference post for Powershell command line usage to achieve different tasks. Recently I had to perform various administration tasks on more than 20 windows based servers , and using scripting it made my life a bit easier and I let the scripting  do the task on my behalf on scheduled basis 😉

These are very common tasks, commands but when you combine them with the Linux shell, they become ultra powerful and best thing is that you can create / add  some ‘ Artificial Intelligence ‘ in it. I have posted just basic level to hide the sensitivity of original tasks.

Following is collection of my own R&D, some commands are picked from Stackoverflow/Spicework forums as well.


General PowerShell Related CMD

Script to send email users lsit who have not logged in last 30 days using BLAT email too

@echo off
cls
set srvname=DC01
set description=Domain Controller DC01 Weekly Report - Users list who have not logged in last 30 days
set jobname=Domain Controller DC01 Weekly Report - Users list who have not logged in last 30 days
set attachment=c:\backup\usersnotloggedlist.log
set tmpfile=c:\backup\usersnotloggedlist_temp.log
set mail-subject=Domain Controller DC01 Weekly Report - Users list who have not logged in last 30 days
set mail-body=Domain Controller DC01 Weekly Report - Users list who have not logged in last 30 days
set mail-to=syed.jahanzaib@XXX.com.pk
set footer=Domain Controller DC01 Weekly Report - Users list who have not logged in last 30 days - Powered by XXX IS Dept.

echo Domain Controller DC01 Weekly Report - Users list who have not logged in last 30 days > %attachment%
echo. >> %attachment%
powershell.exe -inputformat none -command "$DaysInactive = 30; $time = (Get-Date).Adddays(-($DaysInactive)); Get-ADUser -Filter {LastLogonTimeStamp -lt $time -and enabled -eq $true} -Properties * | select Name,UserPrincipalName,Enabled,LockedOut,Created,LastLogonDate,Description" > %tmpfile%

echo Total Count: >> %attachment%
find /C "UserPrincipalName" > %attachment%
echo. >> %attachment%

powershell.exe -inputformat none -command "$DaysInactive = 30; $time = (Get-Date).Adddays(-($DaysInactive)); Get-ADUser -Filter {LastLogonTimeStamp -lt $time -and enabled -eq $true} -Properties * | select Name,UserPrincipalName,Enabled,LockedOut,Created,LastLogonDate,Description" >> %attachment%

echo Powershell Script Powered by XXX IS Dept. >> %attachment%

rem ##########
rem Email LOGS
rem ##########

c:\blat\blat.exe %attachment% -to %mail-to% -i %srvname% -s "%mail-subject%"

rem ## THE END
rem ## Syed Jahanzaib / XXX (Pvt) Ltd. / IS Dept.[/spourcecode]

Output:

<img class=" size-full wp-image-11450 aligncenter" src="https://aacable.files.wordpress.com/2017/02/users-not-logged-in-email-report.png" alt="users not logged in email report" width="808" height="721" />

<hr />

<h2>Clear Event Logs via PS command (runs as admin)</h2>
<pre>wevtutil el | foreach { wevtutil cl $_ }</pre>

<hr />

<h2><strong>Check PowerShell Version</strong></h2>
<pre>$PSVersionTable.PSVersion
Upgrade PowerShell to Version 4 in Windows 7/2008 - 64bit
https://blogs.technet.microsoft.com/heyscriptingguy/2014/11/09/weekend-scripter-install-powershell-4-0-in-windows-7/

Execute Powershell script from Linux Shell using winexe

winexe -U DOMAIN/ID%’PASSWORD’ //IP_OR_NAME //101.11.12.38 ‘powershell.exe -inputformat none -command “dir”‘

winexe -U DOMAIN/ID%’PASSWORD’ //IP_OR_NAME ‘powershell.exe -inputformat none -command “c:\scripts\script_name.ps1″‘


Check Powershell Version & Process Architecture

#Check PowerShell Version
$PSVersionTable
# Check Processor Architecture
$env:PROCESSOR_ARCHITECTURE
# Get list of installed HOTFIX with details
Get-HotFix | Format-Table

 # Import Active Directory module

import-module activedirectory

Show folders that have not been updated/modified by X Period of Time

In my company I have Windows 2008 R2 [as a file sharing / backup server] with a centralized shared folder structure like this

  • D:\USERS
  • D:\USERS\USER1
    D:\USERS\USER1\AUTOBACKUP
    D:\USERS\USER1\DROP
    D:\USERS\USER1\EXHIBIT
  • D:\USERS\USER2
    D:\USERS\USER2\AUTOBACKUP
    D:\USERS\USER2\DROP
    D:\USERS\USER2\EXHIBIT

There are are around 100+ users folders and all users copy their important data on a daily basis there corresponding AUTOBACKUP folder. Every AUTOBACKUP folder have several sub folders and files in it.

My requirements was to somehow display ONLY the AUTOBACKUP folders name which are not updated in last 1 month, means no file in written in any autobackup or in its subfolders. (I dont requires drop/exhibit folders details as it can be updated by any1 , but autobackup can be updated only by the corresponding user)

Result Something like:

  • D:\USERS\USER1\AUTOBACKUP – Updated
  • D:\USERS\USER2\AUTOBACKUP – ALERT: Not updated since last month …

or show me result only for users whose auto backup have not updated from past month.

I tried to get result by powershell commands, but it shows me results if some one update the drop/exhibit too, and i want to exclude them in search criteria, the search should be done only in autobackup.

So here was the solution :)~

Get-WmiObject Win32_LogicalDisk -Filter "DriveType='3'" `
 -ComputerName SERVER_NAME | `
 Format-Table `
 @{l="Server";e={$_.SystemName}}, `
 @{l="Drive Letter";e={$_.DeviceID}}, `
 @{l="Free Space on Disk (GB)";e={"{0:n2}" -f ($_.freespace/1gb)}}, `
 @{l="Total Disk Space (GB)";e={"{0:n2}" -f ($_.size/1gb)}}, `
 @{l="Percentage Used";e={ "{0:P2}" -f (1 - ([Int64]$_.FreeSpace / [Int64]$_.Size)) }}

$PrettySizeColumn = @{name="Size";expression={
 $size = $_.Size
 if ( $size -lt 1KB ) { $sizeOutput = "$("{0:N2}" -f $size) B" }
 ElseIf ( $size -lt 1MB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1KB)) KB" }
 ElseIf ( $size -lt 1GB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1MB)) MB" }
 ElseIf ( $size -lt 1TB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1GB)) GB" }
 ElseIf ( $size -lt 1PB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1TB)) TB" }
 ElseIf ( $size -ge 1PB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1PB)) PB" }
 $sizeOutput
}}

# change the folder name here ...
Get-ChildItem 'D:\USERS' -Directory | ForEach-Object {

$RecentAutoBackupFiles = @(
# change the folder name here too ...
 Get-ChildItem -Path "D:\USERS\$($_.Name)\autobackup" -File -Recurse |
 Where-Object { $_.LastWriteTime -ge [datetime]::Now.AddMonths(-1) }
)

if (0 -eq $RecentAutoBackupFiles.Count)
 {
 "$($_.Name) "
 }
}

Result of above Script (which was executed using Linux bash script as usual:) )

1

 

2


Show Folder Size (in GB) | Sort by Size | Select top 10

This was intense task for me, and I was not able to sort it on my own. so I have to take help from stackoverflow and spicework forums.

Scenario:

We have a Windows 2008 R2  base file server where users have there shared folders.
Example:

  • D:\USERS
  • D:\USERS\USER1
  • D:\USERS\USER2
  • D:\USERS\USER3
  • D:\USERS\USER4
  • D:\USERS\USER5

All users folders have several hundreds sub folders in it.

Task:

Execute functions from Linux base system , which should remote to file server by winexe, execute powershell script, which should perform functions like

  • List all users folder name
  • Last modified time
  • Size conversion auto in kb/mb/gb ( order by size)
  • Email the result [customized] using sendEmail / gmail.

First the powershell script name foldersize.ps1 which will actually perform the functions on file server. we will copy this script in c:\temp on remote file server.

foldersize.ps1


param ($Path = ".")
$disk = ([wmi]"\\FILESERVER\root\cimv2:Win32_logicalDisk.DeviceID='D:'")
"D: GB Total = {0:#.0}
D: GB Used {2:#.0}
D: GB Free {1:#.0} " -f ($disk.Size/1GB),($disk.FreeSpace/1GB),($disk.Size/1GB-$disk.FreeSpace/1GB) | write-output

Get-WmiObject Win32_LogicalDisk -Filter "DriveType='3'" `
-ComputerName FILESERVER | `
Format-Table `
@{l="Server";e={$_.SystemName}}, `
@{l="Drive Letter";e={$_.DeviceID}}, `
@{l="Free Space on Disk (GB)";e={"{0:n2}" -f ($_.freespace/1gb)}}, `
@{l="Total Disk Space (GB)";e={"{0:n2}" -f ($_.size/1gb)}}, `
@{l="Percentage Used";e={ "{0:P2}" -f (1 - ([Int64]$_.FreeSpace / [Int64]$_.Size)) }}

$PrettySizeColumn = @{name="Size";expression={
$size = $_.Size
if ( $size -lt 1KB ) { $sizeOutput = "$("{0:N2}" -f $size) B" }
ElseIf ( $size -lt 1MB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1KB)) KB" }
ElseIf ( $size -lt 1GB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1MB)) MB" }
ElseIf ( $size -lt 1TB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1GB)) GB" }
ElseIf ( $size -lt 1PB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1TB)) TB" }
ElseIf ( $size -ge 1PB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1PB)) PB" }
$sizeOutput
}}

Get-ChildItem -Path $Path | Where-Object {$_.PSIsContainer} | ForEach-Object {
$size = ( Get-ChildItem -Path $_.FullName -Recurse -Force | where {!$_.PSIsContainer} | Measure-Object -Sum Length).Sum
$obj = new-object -TypeName psobject -Property @{
Path = $_.Name
Time = $_.LastWriteTime
Size = $size
}
$obj
} | Sort-Object -Property Size -Descending | Select-Object Path, Time, $PrettySizeColumn

try to execute this file on the file server from powershell terminal. It should give you proper results. JUST BE VERY SURE TO READ THE SCRIPT VERY WELL, AS IT SHOULD BE MODIFIED AS PER YOUR REQUIREMENTS, PLUS I USED DOMAIN ADMIN ID, SO I HAD ALL THE ACCESS ON ALL THE COMPUTERS FROM MY PC /REMOTELY AS WELL.

.\foldersize.ps1 -Path  \\FILESERVER\C$\Softwares\IMAGES_ISO

Once done,  make a bash script in your linux (ubuntu) system  which will execute the above script remotely and will customized the result and email to the admin.

BASH FILE / folder_iquiry.sh which will run the ps file from linux terminal


#!/bin/bash
#set -x
# This bash script will query remote file server storage using Powershell Commands.
# It will send report via email with relevant details like top used folders , Very useful some times.
# Syed Jahanzaib / aacableAThotmailDOTcom
# http://aacableDOTwordpressDOTcom
# 20-feb-2017
start=`date +%s`
COMPANY="ZAIB"
SRVNAME="SRV01"
SRV_FRIENDLY_NAME="File Server D:Drive"
IP="10.0.0.1"
DOMAIN="DC.LOCAL"
PASS="PASSWORD"
ID="ADMIN"
#TARGET DIRECTORY
TDIR="d:\users"
TEMP_HOLDER="/tmp/xdrive_temp_raw_report.txt"
TEMP_HOLDER_FINAL="/tmp/xdrive_final_mail_report.txt"
> $TEMP_HOLDER
> $TEMP_HOLDER_FINAL
DATE=`date`

# GMAIL DETAILS to send EMAIL alert
SENDMAILAPP="/temp/sendEmail-v1.56/sendEmail"
GMAILID="ADMIN_GMAIL_ID@gmail.com"
GMAILPASS="GMAIL_PASS"
# Add recipient email address below
ADMINMAIL1="aacableAThotmailDOTcom"

MSG_SUB="$COMPANY $SRV_FRIENDLY_NAME - $SRVNAME - / Weekly Report @ $DATE"
MSG_BODY="$COMPANY $SRV_FRIENDLY_NAME - $SRVNAME - Weekly Report for Users D: drive folder's sorted by size
@ $DATE
"

FOOTER="Automated Weekly Report Generated using Linux Powered Powershell !!
Sys. Admin
$COMPANY IS Dept."

echo "
$MSG_BODY
" > $TEMP_HOLDER

#QUERY SERVER X: DRIVE
winexe -U $DOMAIN/$ID%"$PASS" //$IP 'powershell.exe -inputformat none -command "c:\temp\foldersize.ps1 -Path '"$TDIR"' ' >> $TEMP_HOLDER

# Remove Junk Line with unknonw character, which is unique or specific occured in my lab test

end=`date +%s`
echo "It took $(($end - $start)) seconds to complete this task..." >> $TEMP_HOLDER
echo "
$FOOTER" >> $TEMP_HOLDER

#Print result
cat $TEMP_HOLDER
#send email
sendemail -u "$MSG_SUB" -o tls=yes -s smtp.gmail.com:587 -t $ADMINMAIL1 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$TEMP_HOLDER -o message-content-type=text

# Script ends here

Now execute file from linux terminal like this…

/temp/folder_inquiry.sh

SAMPLE:

userreport.PNG


Show Folder Size (in GB) | Sort by Size | Select top 10

[This method have one BIG disadvantage, dueto 260 characters limit in windows, it may not show files/folders above then this limit. so it may not give your correct result if you have some deep folder structure/long files name in it.]

#Windows PS Version
ls c:\temp | select Name, @{Name="Type";Expression={if($_.psIsContainer){"---Directory---"}else{"---File---"}}}, @{Name="Size(GB)";Expression={[Math]::Round($(ls $_.FullName -recurse| measure Length -sum).Sum/1GB, 2)}}| sort -property "Size(GB)" -desc | Select -First 10

# Linux Winexe format
winexe -U DC/ID%PASS //IP 'powershell.exe -inputformat none -command "ls c:\backup\ | select Name, @{Name='"'"'"Type"'"'"';Expression={if($_.psIsContainer){'"'"'"Directory"'"'"'}else{'"'"'"File"'"'"'}}}, @{Name='"'"'"Size(GB)"'"'"';Expression={[Math]::Round($(ls $_.FullName -recurse| measure Length -sum).Sum/1GB, 3)}}| sort -property '"'"'"Size(GB)"'"'"' -desc | Select -First 10"'

Example of C:\temp contents …

  • C:\TEMP
  • C:\TEMP\FOLDER1
  • C:\TEMP\FOLDER-1\SUB_FOLDER
  • C:\TEMP\FOLDER-1\SUB_FOLDER_MORE
  • C:\TEMP\FOLDER2
  • C:\TEMP\FOLDER3

This will query all folders/sub-folders inside the c:\temp folder, and display only the main folders name including sizes of subfolder as well ..

Name Type Size(GB)
---- ---- --------
Win2008_test Directory 28.9
Ubuntu-PHP-API Directory 2.75
ubuntu-freeradius Directory 2.15
zaib_temp_radius Directory 2.09
MIKROTIK-1 - Copy Directory 0.39


Show files with Name & Size greater than 5 GB

[This was required in a script where I schedule it to email the top users in mail server by querying the folder directly]

Following command is formatted to be executed by WINEXE [Linux]

winexe -U $DOMAIN/$ID%"$PASS" //$IP 'powershell.exe -inputformat none -command "Get-ChildItem -Path '"$TDIR"' | Where-Object {$_.length -gt 5GB} | Sort-Object -descending -Property Length | Format-Table Name,@{name='"'"'Size GB'"'"';expression={$_.length/1GB};FormatString='"'"'N1'"'"'}"' | sed -e "$DEL_LINE" | sed '/^\s*$/d' |nl >> $TEMP_HOLDER

Script to get specific folder files and specific  folder total size, sort and email to admin on every Monday / Weekly

#!/bin/bash
#set -x
# This bash script will query remote lotus domino mail server storage using Powershell Commands.
# It will send report via email with erelevant details, Very useful some times.
# Syed Jahanzaib / aacableAThotmailDOTcom
# http://aacableDOTwordpressDOTcom
# 20-feb-2017
COMPANY="ZAIB"
SRVNAME="MYSRV"
IP="10.0.0.1"
DOMAIN="DC_NAME"
PASS="PASSWORD"
ID="ADMINISTRATOR"
TDIR="D:\lotus\domino\data\mail"
TDIR_FULL="D:\lotus"
TDIR_MAIL="D:\lotus\domino\data\mail"
TDIR_ARCH="D:\lotus\domino\data\archive"
# How many lines to be dleeted from winexe output for top users section
DEL_LINE="1,3d"
TEMP_HOLDER="/tmp/mail_top_users.txt"
TEMP_HOLDER_FULL="/tmp/mail_lotus_folder_size.txt"
> $TEMP_HOLDER
DATE=`date`

# GMAIL DETAILS to send EMAIL alert
SENDMAILAPP="/temp/sendEmail-v1.56/sendEmail"
GMAILID="ADMIN_GMAIL_ID@gmail.com"
GMAILPASS="GMAIL_PASSWORD"
# Add recipient email address below
ADMINMAIL1="aacableAThotmailDOTcom"

MSG_SUB="$COMPANY Lotus Mail Server / Weekly Report @ $DATE"
MSG_BODY="$COMPANY - $SRVNAME - Lotus Mail Server Weekly Report for Total Usage and TOP users exceeding 5GB mailbox size
@ $DATE
"
FOOTER="Automated Weekly Report Generated using Linux Powered Powershell !!
Sys. Admin
$COMPANY IS Dept."

echo "
$MSG_BODY
" > $TEMP_HOLDER

#Full size of Lotus Folder - Overall
FULL_SIZE=`winexe -U $DOMAIN/$ID%"$PASS" //$IP 'powershell.exe -inputformat none -command " "\"{0:N0}"\" -f ( (Get-ChildItem -Path '"$TDIR_FULL"' -Recurse | Measure-Object -Property Length -Sum ).Sum / 1GB)"' |sed '/^\s*$/d'`
echo "Lotus Total DATA size in GB = $FULL_SIZE" >> $TEMP_HOLDER

#Full size of Lotus MAIL Folder only
FULL_SIZE_MAIL=`winexe -U $DOMAIN/$ID%"$PASS" //$IP 'powershell.exe -inputformat none -command " "\"{0:N0}"\" -f ( (Get-ChildItem -Path '"$TDIR_MAIL"' -Recurse | Measure-Object -Property Length -Sum ).Sum / 1GB)"' |sed '/^\s*$/d'`
echo "Lotus Total User Inbox MAIL SIZE in GB = $FULL_SIZE_MAIL" >> $TEMP_HOLDER

#Full size of Lotus ARCHIVE Folder only
FULL_SIZE_ARCH=`winexe -U $DOMAIN/$ID%"$PASS" //$IP 'powershell.exe -inputformat none -command " "\"{0:N0}"\" -f ( (Get-ChildItem -Path '"$TDIR_ARCH"' -Recurse | Measure-Object -Property Length -Sum ).Sum / 1GB)"' |sed '/^\s*$/d'`
echo "Lotus User's ARCHIVE Folder SIZE in GB = $FULL_SIZE_ARCH" >> $TEMP_HOLDER

echo "----------------------------------------------
Lotus Users List whose inbox is exceeding 5 GB" >> $TEMP_HOLDER

#Only Top users exceeding 5GB
winexe -U $DOMAIN/$ID%"$PASS" //$IP 'powershell.exe -inputformat none -command "Get-ChildItem -Path '"$TDIR"' | Where-Object {$_.length -gt 5GB} | Sort-Object -descending -Property Length | Format-Table Name,@{name='"'"'Size GB'"'"';expression={$_.length/1GB};FormatString='"'"'N1'"'"'}"' | sed -e "$DEL_LINE" | sed '/^\s*$/d' |nl >> $TEMP_HOLDER

echo "

$FOOTER" >> $TEMP_HOLDER
# Display result by cat
cat $TEMP_HOLDER
# Send email
sendemail -u "$MSG_SUB" -o tls=yes -s smtp.gmail.com:587 -t $ADMINMAIL1 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$TEMP_HOLDER -o message-content-type=text

Result of above script …

1.PNG


PowerShell Get Folder / File ACL list

Get-Acl c:\temp | select -Expand Access

Sample Result:


PS C:\> Get-Acl c:\temp | select -Expand Access
FileSystemRights : FullControl
AccessControlType : Allow
IdentityReference : BUILTIN\Administrators
IsInherited : True
InheritanceFlags : None
PropagationFlags : None

FileSystemRights : 268435456
AccessControlType : Allow
IdentityReference : BUILTIN\Administrators
IsInherited : True
InheritanceFlags : ContainerInherit, ObjectInherit
PropagationFlags : InheritOnly

FileSystemRights : FullControl
AccessControlType : Allow
IdentityReference : NT AUTHORITY\SYSTEM
IsInherited : True
InheritanceFlags : None
PropagationFlags : None

FileSystemRights : 268435456
AccessControlType : Allow
IdentityReference : NT AUTHORITY\SYSTEM
IsInherited : True
InheritanceFlags : ContainerInherit, ObjectInherit
PropagationFlags : InheritOnly

FileSystemRights : ReadAndExecute, Synchronize
AccessControlType : Allow
IdentityReference : BUILTIN\Users
IsInherited : True
InheritanceFlags : ContainerInherit, ObjectInherit
PropagationFlags : None

FileSystemRights : Modify, Synchronize
AccessControlType : Allow
IdentityReference : NT AUTHORITY\Authenticated Users
IsInherited : True
InheritanceFlags : None
PropagationFlags : None

FileSystemRights : -536805376
AccessControlType : Allow
IdentityReference : NT AUTHORITY\Authenticated Users
IsInherited : True
InheritanceFlags : ContainerInherit, ObjectInherit
PropagationFlags : InheritOnly

PS C:\>


Regard’s
Syed Jahanzaib

Older Posts »

%d bloggers like this: