PowerShell for system administration work

Since Windows Server 2000, VB script has been the primary language for doing system administration work. The philosophy and design were to provide more scripting features than the .bat or .cmd batching programming. As .NET evolves, developers build sophisticated applications in Visual Studio. But that did not solve the problems VB script was solving. When Microsoft shipped PowerShell, developers or system administrators finally could get out of the VB script hell. As an engineer at Microsoft IT, it’s common to use scripts to manage servers. One thing I learned is that it takes about 6 times more effort to develop scripts in VB than in PowerShell. Most of the time wasted is in debugging VB scripts. I am listing some useful PowerShell scripts I’ve learned:

# Creating MSMQ
[Reflection.Assembly]::LoadWithPartialName("System.Messaging")
$q = [System.Messaging.MessageQueue]::Create(".\private$\organization.response", $true) # true means create transactional queue
# check if UAC is enabled in Windows Server 2008
$UAC = Get-ItemProperty -Path registry::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\policies\system -Name EnableLUA
if ($UAC.EnableLUA -eq 1) # UAC is enabled
# Get the current running script path
$ScriptDirPath = Split-Path -Parent -Path $myInvocation.MyCommand.Path
# Check if WMI software is installed
$Product = Get-WmiObject -Class Win32_product

$ProductClient = $Product | ? { $_.Name -like "*PRODUCT*Client*" }

$ProductServer = $Product | ? { $_.Name -like "*PRODUCT*Server*" }
# Get the previous Exception
$Error[0].Exception
# If there is an exception, abort the script
trap
{
Write-Error $("TRAPPED: " + $_.Exception.GetType().FullName);
Write-Error $("TRAPPED: " + $_.Exception.Message);
exit 1
}
# Get the current windows user
$userName = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
# enable script to take argument switches. Put it at the top of the script
Param(
[string]$VMDirPath = $(throw "Please specify -VMDirPath"),
[string]$VM_Name = $(throw "Please specify -VM_Name")
)

If you want ADO.NET examples, read https://blogs.technet.com/threekings/default.aspx