Knowledge Base - http://www.blog.klyavlin.ru

My new blog

February 2, 2013 Leave a comment

Blog is moved to new domain, please update you shortcuts ❤

Knowledge Basehttp://www.blog.klyavlin.ru

Categories: Uncategorized

How to schedule PowerShell script

October 14, 2012 Leave a comment
To schedule PowerShell script you need to run powershell.exe with following parameters:
PowerShell.exe -command &'full_path_to_script.ps1'
  • Full path to powershell.exe is also recommended

List Active Directory group members

October 8, 2012 Leave a comment
Simplest way to get AD group members is to use one cmdlet: 
Get-ADGroupMember "group_name"

But this cmdlet contains poor amount of properties to use. And if you need load more information about listed users you can pipeline results to another cmdlet with lots of properties: Get-ADUser.
Below is example of group members list sorted by Display Name. You can select any property similar way.

Import-Module ActiveDirectory
# There is an inputbox for group name #
$gr_name=Read-Host "Input AD group name:"
# Results of Get-ADGroupMember pipelined to Get-ADUser as input #
# Display Name property selected and sort-order is set. #
Get-ADGroupMember $gr_name | Get-ADUser -properties displayname | select DisplayName | Sort-Object -Property displayname
Write-Host "-----------"
  • Script language: PowerShell
  • Read permissions to AD required

Restart WiFi adapter if it hangs

October 8, 2012 1 comment
My Wi-Fi connection with home D-Link router freezes sometimes. I don’t really know why, but it mostly happens during video streaming or p2p downloading. But I have founded that restarting wireless network adapter helps. It doesn’t take much time to restart adapter and I decided to solve wi fi hanging issue next way: wright script which restarts wifi connection if its hangs.
I use this script on my laptop half a year already. It triggers every minute and works fine.

  • Script language: VBScript
  • Changing Network Adapter setting requires administrative privileges.

Script Block

To get full script copy code from blocks one by one.

Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")
Set colWiFi=objWMIService.ExecQuery ("SELECT * FROM Win32_NetworkAdapter")

ArrRemoteHosts = Array("ya.ru","8.8.8.8","google.com")
FailCount = 0

First of all we connect to local WMI and selecting all network adapters. Then creating array of remote hosts ( ArrRemoteHosts ). We will ping them to determine Wi-Fi connection state. There are several hosts to be sure that the problem not in remote host, but in Wi-Fi connection. FailCount var is used to store remote host state.

FOR EACH WiFi in colWiFi
IF InStr(1, WiFi.name, "wireless", 1) > 0 THEN
IF WiFi.NetEnabled = "True" THEN

Now we gonna parse list of selected adapters to find the one, which name contains “wireless“. That is what we need, but need to check is it enabled or not. Because you could disable it yourself and scheduled script will enable it back – not cool.

    FOR EACH RemoteHost in ArrRemoteHosts
Set colPing=objWMIService.ExecQuery ("SELECT * FROM Win32_PingStatus WHERE Address = '" & RemoteHost & "'")
FOR EACH ping in colPing
IF ping.StatusCode = 0 and ping.ResponseTime < 300 THEN
WScript.Quit
ELSE
FailCount = FailCount + 1
END IF
NEXT
NEXT

Once we found right network adapter we start to checking remote hosts accessibility. IF StatusCode = 0 there is no error during ICMP exchange. But I found that sometimes wifi freezes not completely and ping actually pathing through but ResponceTime incredible high. So its equals offline state of wifi. If both parameters are fine while pinging first host in array – script quits, but if its not – FailCount increase. Quit after first successfully pinged remote host makes script “lighter” especially if its scheduled, for example, once per minute.

    IF FailCount = 3 THEN
WiFi.Disable()
WScript.Sleep 3000
WiFi.Enable()
END IF
END IF
END IF
NEXT

On the last step we check FailCount and if all three remote host output an error or pings too high – network adapter state is changing to disabled and then back to enabled. Sleep is used for timeout while state is changing.

Categories: Networks, Scripting

Changing Network Adapter settings from Static to Automatic DHCP

October 7, 2012 Leave a comment
The task is to re-configure Network Adapter settings on client computers during reorganization of branch office. I used local script because branch office computers are not in domain. Also it is a VBScript because client OS is Windows XP, otherwise I would use PowerShell.
See detail explanation in code blocks below. To get full script – copy code form each block one by one.

  • Script language: VBScript
  • Changing Network Adapter setting requires administrative privileges.

Code Block #1

badstate = 0
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colNetAdapters = objWMIService.ExecQuery ("Select * from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE")
FOR EACH objNetAdapter In colNetAdapters
errEnable = objNetAdapter.EnableDHCP()
IF errEnable = 0 THEN
Wscript.Echo "DHCP is turned on."
ELSE
Wscript.Echo "DHCP is NOT turned on."
badstate = 1
END IF
NEXT

badstate is a flag which is used on the last step to determine are settings applied successfully or not. Next we connecting to local computer ( “.” ) WMI and executing query to select all Network Adapters where TCP/IP is enabled ( IPEnabled=TRUE ). Once we selected the adapter we need to turn on DHCP in it. We use ( EnableDHCP() ) method to set “Obtain an IP address automatically” option in TCP/IP Properties. Using errEnabled var to catch error codes if they appear. Echo will report the result and badstate flag will change to 1 if there is an error.

Code Block #2

On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colNetCards = objWMIService.ExecQuery ("Select * From Win32_NetworkAdapterConfiguration Where IPEnabled = True")
FOR EACH objNetCard in colNetCards
arrDNSServers = objNetAdapter.EnableDHCP()
errEnable = objNetCard.SetDNSServerSearchOrder(arrDNSServers)
IF errEnable = 0 THEN
Wscript.Echo "DNS is turned on."
ELSE
Wscript.Echo "DNS is NOT turned on."
badstate = 1
END IF
NEXT

Now its time to change DNS settings to “Obtain DNS server address automatically” in TCP/IP Properties. We connecting again to local computer ( “.” ) WMI and executing query to select all Network Adapters where TCP/IP is enabled ( IPEnabled=TRUE ). Why? Because with DNS its a bit harder. You should provide DNS server list ( arrDNSServers ), which you are receiving by DHCP, using SetDNSServerSearchOrder(arrDNSServers) method. Also use errEnabled var to catch error codes if they appear. Echo will report the result and badstate flag will change its value to 1 if there is an error. On Error Resume Next statement recommended.

Code Block #3

This block is used to change client computer membership in Workgroup. Feel free to skip it.
strComputer = "."
strWorkGroup = "WORKGROUP"
Set objNetwork = CreateObject("WScript.Network")
strComputer = objNetwork.ComputerName
Set objComputer = GetObject("winmgmts:{impersonationLevel=Impersonate}!\\" & strComputer & "\root\cimv2:Win32_ComputerSystem.Name='" & strComputer & "'")
errEnable = objComputer.JoinDomainOrWorkGroup(strWorkgroup, NULL, NULL, NULL, 0)
IF errEnable = 0 THEN
Wscript.Echo "Workgroup is changed."
ELSE
Wscript.Echo "Workgroup is NOT changed."
badstate = 1
END IF

strWorkGroup contains name of Workgroup you would like to join.
Connecting to WMI to get computer object and use JoinDomainOrWorkGroup() method. Echo and errEnabled here for same purpose as before.

Code Block #4

IF badstate <> 1 THEN
Wscript.Echo "All settings applied successfully. Restart in 1 minute."
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "C:\WINDOWS\system32\shutdown.exe -r -t 60"
END IF

In the end we check state of badstate flag, and if its not being triggered return message about successful applying of all settings and restart computer.
Note: restart is required after changing Workgroup, if you skipped this part you may not restart computer.

nslookup

October 5, 2012 Leave a comment
Windows integrated command to generate DNS queries. Also useful for troubleshooting DNS issues, or testing new DNS records and etc.

nslookup syntax:
nslookup –type=”record type” “ip/name to resolve” “dns server to ask for
if parameter is empty next defaults is used:

type default A-record
dns server to ask for default Network Connection DNS settings
Query examples:
nslookup ya.ru 8.8.8.8                 // default A-record query
nslookup -type=ptr 8.8.4.4 8.8.8.8 // PTR-record query
nslookup -type=mx google.com 8.8.8.8 // MX-record query
Categories: DNS, Networks

Windows Hotkey

October 5, 2012 Leave a comment
Improve your work speed using GUI-independant hotkeys!

Keys to press Description
Windows+R Run (see details)
Ctrl+Shift+N create a new folder
Ctrl+Shift+Esc Task Manager
Ctrl+Alt+PauseBreak minimize active RDP window
Alt+Space+X maximize active window
Alt+Space+R restore active window
Alt+Space+N minimize active window
Alt+V+D change folder view to Detailed

Win+R Capabilities

October 5, 2012 Leave a comment
Win+R is powerfull instrument for working in any Windows OS because of independence from GUI, which can change in time.

Command Description
cmd CMD interface
calc Windows Calculator
compmgmt.msc Computer Management
ncpa.cpl Network Connections
devmgmt.msc Device Manager
eventvwr Event Viewer
outlook MS Outlook
winword MS Word
excel MS Excel
%temp% user Temp folder
%appdata% user Application Data folder
%windir% Windows system folder
gpedit.msc Local Group Policy Editor
rsop.msc Resultant set of Policy

Send e-mail from freeBSD

October 5, 2012 Leave a comment


/usr/bin/mail -s “Subject” user@domain.com <<< “Body”

Categories: freeBSD, Scripting

Running System Utilities from Console

October 5, 2012 2 comments
Console ( Win+R ) is GUI-independent administrative tool. It really helps a lot while working with new Windows versions or customized GUI. In my opinion having those commands in your head better than remembering  their locations in different versions of graphical user interface. Of course its not a full list.

[EN] Name [RU] Name Command to Run
Add Hardware Wizard (установка оборудования) hdwwiz.cpl
Add/Remove Programs (установка/удаление программ) appwiz.cpl
Administrative Tools (администрирование) control admintools
Automatic Updates (Автоматическое обновление) wuaucpl.cpl
Automatic Updates (Автоматическое обновление) control update
Bluetooth Transfer Wizard (?) fsquirt
Calculator (калькулятор) calc
Certificate Manager (Менеджер сертификатов) certmgr.msc
Character Map (Таблица символов) charmap
Check Disk Utility (Проверка диска) chkdsk
Clipboard Viewer (Просмотр буфер обмена) clipbrd
User Accounts Учетные записи control userpasswords
Command Prompt (Командная строка) cmd
Component Services (Служба компонентов) dcomcnfg
Computer Management (Управление компьютером) compmgmt.msc
Date and Time Дата и время timedate.cpl
DDE Shares Общие ресурсы DDE ddeshare
Device Manager (Диспетчер устройств) devmgmt.msc
Direct X Control Panel (Панель управления Direct X) directx.cpl
Direct X Troubleshooter (Диагностика Direct X) dxdiag
Disk Cleanup Utility (Мастер очистки диска) cleanmgr
Disk Defragment (Дефрагментация) dfrg.msc
Disk Management (Управление дисками) diskmgmt.msc
Disk Partition Manager (Управление разделами) diskpart
Display Properties (Свойства: Экран) control desktop
Display Properties (Свойства: Экран) desk.cpl
Display Properties (w/Appearance Tab Preselected) (у меня Свойства: Экран/заставка) control color
Dr. Watson System Troubleshooting Utility (Отладчик Dr. Watson) drwtsn32
Driver Verifier Utility (Диспетчер проверки драйверов) verifier
Event Viewer (Просмотр событий) eventvwr.msc
File Signature Verification Tool (Проверка сигнатур системных файлов) sigverif
Findfast (Вроде быстрый поиск? в XP Prof Sp1 не нашел ) findfast.cpl
Folders Properties (Свойства папки) control folders
Fonts control (Папка Шрифты) fonts
Fonts Folder (Папка Шрифты) fonts
Free Cell Card Game (Игра Солитер) freecell
Game Controllers (Игровые устройства) joy.cpl
Group Policy Editor (XP Prof) (Групповые политики) gpedit.msc
Hearts Card Game (Игра «Черви») mshearts
Iexpress Wizard (Мастер встроенного архиватора iexpress) iexpress
Indexing Service (Служба индексирования) ciadv.msc
Internet Properties (Свойства:Интернет) inetcpl.cpl
IP Configuration (Display Connection Configuration) (Отобразить полную информацию о настройке параметров) ipconfig /all
IP Configuration (Display DNS Cache Contents) (Отобразить содержимое кэша ДНС) ipconfig /displaydns
IP Configuration (Delete DNS Cache Contents) (Очистить кэш разрешений ДНС) ipconfig /flushdns
IP Configuration (Release All Connections) (Освободить IP-адрес для указанного адаптера) ipconfig /release
IP Configuration (Renew All Connections) (Обновить IP-адрес для указанного адаптера) ipconfig /renew
IP Configuration (Refreshes DHCP & Re-Registers DNS) (Обновление DHCP-аренды и перерегистрация ДНС) ipconfig /registerdns
IP Configuration (Display DHCP Class ID) (Отобразить все допустимые для этого адаптера коды DHCP-классов) ipconfig /showclassid
IP Configuration (Modifies DHCP Class ID) (изменить код DHCP-класса) ipconfig /setclassid
Java Control Panel (If Installed) (Панель управления Java) jpicpl32.cpl
Java Control Panel (If Installed) (Панель управления Java) javaws
Keyboard Properties (Свойства: клавиатура) control keyboard
Local Security Settings (Настройки безопасности) secpol.msc
Local Users and Groups (Локальные пользователи и группы) lusrmgr.msc
Logs You Out Of Windows (Завершение сеанса) logoff
Microsoft Chat (Чат) winchat
Minesweeper Game (Игра сапер) winmine
Mouse Properties (Свойства:мышь) control mouse
Mouse Properties (Свойства:мышь) main.cpl
Network Connections (Сетевые подключения) control netconnections
Network Connections (Сетевые подключения) ncpa.cpl
Network Setup Wizard (Мастер сетевых подключений) netsetup.cpl
Notepad (Запуск Блокнота) notepad
Nview Desktop Manager (If Installed) (имхо, менеджер рабочего стола Nvidia) nvtuicpl.cpl
Object Packager (Упаковщик объектов) packager
ODBC Data Source Administrator (Администратор источников данных ODBC) odbccp32.cpl
On Screen Keyboard (Экранная клавиатура) osk
Opens AC3 Filter (If Installed) (?) ac3filter.cpl
Password Properties (имхо, Свойства:пароль) password.cpl
Performance Monitor (Производительность) perfmon.msc
Performance Monitor (Производительность) perfmon
Phone and Modem Options (Свойства:телефон и модем) telephon.cpl
Power Configuration (Свойства:электропитание) powercfg.cpl
Printers and Faxes (Принтеры и факсы) control printers
Printers Folder (Папка принтеры) printers
Private Character Editor (Редактор символов) eudcedit
Quicktime (If Installed) (?) QuickTime.cpl
Regional Settings (Язык и региональные стандарты) intl.cpl
Registry Editor (Редактор реестра) regedit
Registry Editor (редактор реестра платформа х32) regedit32
Remote Desktop (Удаленный рабочий стол) mstsc
Removable Storage (Съемные запоминающие устройства) ntmsmgr.msc
Removable Storage Operator Requests (Запросы операторов съемных запоминающих устройств) ntmsoprq.msc
Resultant Set of Policy (XP Prof) (Результирующая политика) rsop.msc
Scanners and Cameras (Сканеры и камеры) sticpl.cpl
Scheduled Tasks control (Планировщик заданий) schedtasks
Security Center (Центр безопасности) wscui.cpl
Services (Службы) services.msc
Shared Folders (Расшареные папки) fsmgmt.msc
Shuts Down Windows (Завершение работы) shutdown
Sounds and Audio (Свойства: звуки и аудиоустройства) mmsys.cpl
Spider Solitare Card Game (Пасьянс Паук) spider
SQL Client Configuration (Программа сетевого клиента SQL-сервера) cliconfg
System Configuration Editor (Редактор файлов настройки) sysedit
System Configuration Utility (Утилита настройки системы) msconfig
System File Checker Utility (Scan Immediately) (Сканирование дисков/начать сразу) sfc /scannow
System File Checker Utility (Scan Once At Next Boot) (Сканирование дисков/один раз при следующей загрузке) sfc /scanonce
System File Checker Utility (Scan On Every Boot) (Сканирование дисков/каждый раз при загрузке) sfc /scanboot
System File Checker Utility (Return to Default Setting) (Сброс на установки по умолчанию) sfc /revert
System File Checker Utility (Purge File Cache) (Очистка фалового кэша) sfc /purgecache
System File Checker Utility (Set Cache Size to size x) (Установка размера кэша) sfc /cachesize=x
System Properties (Свойства системы) sysdm.cpl
Task Manager (Диспетчер задач) taskmgr
Telnet Client (Телнет-клиент) telnet
User Account Management (Учетные записи пользователей) nusrmgr.cpl
Utility Manager (Менеджер служебных программ) utilman
Windows Firewall (Брандмауэр Windows) firewall.cpl
Windows Magnifier (Экранная лупа) magnify
Windows Management Infrastructure (Инфраструктура управления Windows (WMI)) wmimgmt.msc
Windows System Security Tool (Защита базы данных учетных записей) syskey
Windows Update Launches (Запуск службы обновлений) wupdmgr
Windows XP Tour Wizard (Запуск знакомства с Windows) tourstart
Wordpad (Запуск редактора Wordpad) write
Design a site like this with WordPress.com
Get started