PowerShell

Newer versions of PowerShell can be installed by downloading and installing Windows Management Framework (WMF).

PowerShell versions

PowerShell 1.0: Released in 2006 for Windows XP SP2, 2003 and Vista. It is an optional component for Windows 2008 Server.

PowerShell 2.0: Available with Windows 7, 2008 R2 and released for XP SP3, 2003 Sp2 and Vista SP1.

PowerShell 3.0: Available with Windows 8, 2012. Released for 7 SP1, 2008 SP1 and 2008 R2 SP1.

PowerShell 4.0: Available with Windows 8.1, 2012 R2. Released for 7SP1, 2008 R2 SP1 and 2012.

PowerShell 5.0: Available with Windows Management Framework 5.0.

————–

PowerShell cmdlets (pronounced command lets) naming convention

verb-noun

All the noun in PowerShell cmdlets are singular. Ex: get-service is correct and get-services is wrong.

————–

PowerShell Direct

Running PowerShell commands inside a virtual machine from the host operating system easily and reliably.

There are no network/firewall requirements or configurations.
It works regardless of Remote Management configuration.
You still need guest credentials.

Allowing scripts to execute in PowerShell:

Set-ExecutionPolicy RemoteSigned

To Import Active Directory modules into PoweShell:

Import-Module ActiveDirectory

The Set-ExecutionPolicy cmdlet enables you to determine which Windows PowerShell scripts (if any) will be allowed to run on your computer. Windows PowerShell has four different execution policies:

  • Restricted – No scripts can be run. Windows PowerShell can be used only in interactive mode.
  • AllSigned – Only scripts signed by a trusted publisher can be run.
  • RemoteSigned – Downloaded scripts must be signed by a trusted publisher before they can be run.
  • Unrestricted – No restrictions; all Windows PowerShell scripts can be run.

——————

How to find PowerShell version ?

$PSVersionTable

 

PowerShell script to start or stop service on remote server(s)

Syntax:

Get-Service -Computer Computername -name servicename | start-service -verbose

Get-Service -Computer Computername -name servicename | stop-service -verbose

Note: Service name will be sometimes different than the one listed in the services.msc. You need to check it by selecting the properties of the service in services.msc as shown below.

How to find a service name ?

 

Example:

Get-Service -computer Applicationserver100 -name AltirisAgentProvider | Stop-Service -verbose

The above example will stop the AltirisAgentProvider service on Applicationserver100.

————————

PowerShell Help

Starting from Windows 2012 and Windows 8, PowerShell help was removed. You have to update it to use it.

Command:

update-help or update-help -force

  • -force: Rechecks and updates the help contents even though if you have updated the help today.

Command:

get-help get-process -Detailed
get-help get-service -Examples
get-help get-service -full
get-help get-service -ShowWindow

-Detailed provides parameters, Examples etc.
-Examples provides Examples.
-Full provides pages and pages of help. More than detailed.

————————

Useful commands

update-help

help

get-help *process*

get-help new-netipaddress

get-verb

————————

PowerShell script to add a host entry in remote server

function add-host([string]$filename)
{         
$addip = "198.18.2.57"
$addhostname = "Altiris-server"
$addip + "`t`t" + $addhostname | Out-File -encoding ASCII -append $filename
}

foreach ($srv in gc “C:\FileServer.txt”)
{
$file  = “\\”+ $srv  + "\C$\Windows\System32\drivers\etc\hosts"
add-host $file
}

Original:
https://gallery.technet.microsoft.com/scriptcenter/add-remove-entry-from-4a70dcb4

1. PowerShell script to get SQL server versions from a group of servers

$start = get-date
write-host "Start: " $start
 
 [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | out-null
 
$FilePath = "C:\"
$OutFile = Join-Path -path $FilePath -childPath ("SQLVersions_" + (get-date).toString('yyyyMMdd_hhmmtt') + ".log")


 @(foreach ($svr in get-content "C:\Servers.txt")
 {
 $s = New-Object "Microsoft.SqlServer.Management.Smo.Server" $svr
 $s | select Name, Product, ProductLevel, Edition, Version, BuildNumber
 
 }) | export-csv -noType $OutFile
 
 $end = get-date 
 write-host "End: " $end

2. Powershell script to find RAM details on a remote computer

Source: http://community.spiceworks.com/scripts/show/1020-get-amount-of-memory-on-remote-machine

$x = read-host -prompt "Please enter the machine name: "  

$colItems = get-wmiobject -class "Win32_ComputerSystem" -namespace "root\CIMV2" -computername $x

foreach ($objItem in $colItems){
$displayGB = [math]::round($objItem.TotalPhysicalMemory/1024/1024/1024, 0)
write-host "Total Physical Memory: " $displayGB "GB"
write-host "Model: " $objItem.Model
}

$colItems = get-wmiobject -class "Win32_Processor" -namespace "root\CIMV2" -computername $x
foreach ($objItem in $colItems){
write-host "System Name: " $objItem.SystemName
}

Save the above code in a notepad and save it as filename.ps1 Open PowerShell and execute as shown below.
scr
Get list of active users in Active Directory

On Domain controller:
1. Save the below code in a notepad and save as "filename.ps1" in the desktop
2. Open Powershell from start menu
3. Traverse to the desktop and type filename.ps1
4. Once the execution is complete, you can find user_dump.csv in C:\ drive

Get-ADUser -LDAPFilter "(!userAccountControl:1.2.840.113556.1.4.803:=2)" -pr * `
| select givenname, sn, mail, samaccountname, physicalDeliveryOfficeName, telephoneNumber, mobilephone `
| export-csv c:\user_dump.csv -NoTypeInformation

3. PAEXEC tool & TZUTIL tool
PAEXEC is a free tool by Power Admin company. It is like the PSEXEC (Sysinternals by Mark Russinovich) but with few advantages:

You can use this tool to remote execute commands from a central system. For example, you can change the Time zone settings of a remote computer using this tool.

paexec
Here in the above image, Paexec will execute the TZutil command (windows command specifically used to change time related settings) on Machine100. After the execution, Machine100's timezone setting will change to Coordinated Universal time.To change the settings for two machines use
paexec.exe \\machine1, machine2 tzutil /s "utc"

To change the settings on multiple machines use
paexec.exe \\* tzutil /s "utc"

To change the Timezone settings for a set of machines (machine names are entered into a text file)
paexec.exe @complist.txt tzutil /s "utc"

4. Script to get Time zone details of remote machines

Source: http://gallery.technet.microsoft.com/scriptcenter/Query-AD-for-list-of-76b74d5e

#The name you are searching for, wildcards allowed. 
$filter = "dw7*" 
 
#Query AD for computers that match the above filter and make a list of them 
$comps = Get-ADComputer -Filter 'Name -like $filter' | Select -Expand Name 
if (!($comps)) {write-host "No computers matching $filter where found"} 
 
#Roll through computers recovered from AD and get timezone 
 foreach ($comp in $comps) { 
 try { 
 $tz = Get-WMIObject -class Win32_TimeZone -ComputerName $comp -ErrorAction Stop 
 write-host ("$comp has its timezone set to " + $tz.description) 
 } 
 catch [Exception] { #something failed, write the info 
 write-host ("Could not get timezone information from $comp -" + $($_.Exception.Message) ) 
 } 
 $tz="" 
 }

Note: Note the text highlighted in Red. It says Dw7*, which means the script will fetch the Timezone data of machines which starts with the name dw7.

5. Script to get AD User name, Mail, Account name, Telephone and mobile phone numbers of all users in Active directory

Save the below file in somename.ps1 and execute in Powershell (Right click the ps1 file and select run in PowerShell)

Get-ADUser -LDAPFilter “(!userAccountControl:1.2.840.113556.1.4.803:=2)” -pr * ` | select givenname, sn, mail, samaccountname, physicalDeliveryOfficeName, telephoneNumber, mobilephone ` | export-csv c:\user_dump.csv -NoTypeInformation

5. AD replication status check through PowerShell (sends email)

http://technodrone.blogspot.com/2010/04/monitor-ad-replication-status-with.html