Category Archives: Powershell

Windows | DHCP PowerShell Options (Cheatsheet)

Managing DHCP on DHCP server:

Add-WindowsFeature -Name DHCP –IncludeManagementTools

Managing DHCP on remote host:

Add-WindowsFeature RSAT-DHCP

Powershell DHCP Module:

Import-Module DhcpServer

Get all DHCP servers in AD

Get-DhcpServerInDC

Get DHCP scope configuration

Get-DhcpServerv4Scope –ComputerName <DHCPServerName>

Get DHCP reservations on scope:

Get-DhcpServerv4Reservation -ComputerName <DHCPServerName> -ScopeId <ScopeID>

Import/Export DHCP Scopes

netsh dhcp server export C:\temp\DHCP.txt all
netsh dhcp server import C:\temp\DHCP.txt all

Note: The temp folder needs to be created

Check DHCP Replication Failover Status

Get-DhcpServerv4Failover -ComputerName <DHCPServerName>

Reference:
https://technet.microsoft.com/en-us/library/jj590708(v=wps.630).aspx

Windows Dedup | Cheat Sheet

Get dedup status:

Get-DedupStatus

Get dedup status formatted & additional info:

Get-DedupStatus | fl

Get dedup status for specified volumes:

Get-DedupStatus -Volume "D:","F:"

Show Dedup Metadata (How deduplication is being used) on the server:

Get-Dedupmetadata

Show Dedup Metadata for specified volumes:

Get-Dedupmetadata D:

Enable Dedup Job:

Start-DedupJob D: -Type Optimization -Full

Disable Dedup Job:

Start-DedupJob -Type Unoptimization -Volume <Desired-Volume>

Ref: https://docs.microsoft.com/en-us/windows-server/storage/data-deduplication/whats-new

Remove “Windows.old” using Cleanmgr CLI | Windows 10

PowerShell Script for removing the “Windows.old” folder using cleanmgr.exe command line

New-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\Temporary Setup Files' -PropertyType 'DWORD' -Force -Name 'StateFlags1337' -Value 0x2
New-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\Previous Installations' -PropertyType 'DWORD' -Force -Name 'StateFlags1337' -Value 0x2
cleanmgr.exe /SAGERUN:1337

Great post on the syntax of “Cleanmgr.exe”

https://winaero.com/blog/cleanmgr-exe-command-line-arguments-in-windows-10/ 

Migrate Folder Shares | PowerShell

Basic objective, we’ve got a ton of shares which we need to move to a new server. The data has already been replicated but we need to re-share.
There are methods of doing this by exporting the registry but being a little scared of messing up the current shares and requiring a reboot I decided to do this manually…

Export list of shares on source server:

get-WmiObject -class Win32_Share -computer servername.fqdn.com | Export-Csv -Path "C:\Shares.csv"

Create shares on destination server:

Powershell:

Need the powershell command here

CMD Net Share

net share "ShareName"="D:\Path\FolderName" /grant:everyone,FULL

Reference:
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/export-csv?view=powershell-6
https://gallery.technet.microsoft.com/scriptcenter/Creates-New-Share-with-fb22d905
http://www.tomsitpro.com/articles/use-fileshare-powershell-cmdlets-server-2016,2-1053.html

VMware ESX 6.0 to 6.5 Upgrade | vSphere CLI commands

I’ve been working on a project to upgrade vCentre from 6.0 to 6.5. This meant that multiple Dell (R530, R630, R730) hosts required an update of ESX (using Update Manager). Unfortunately these upgrades failed (first time around) due to the custom VIBs within previous Dell Customized Images of ESXi conflicting with native drivers within ESX6.5. Below is the cheat-sheet of commands to remove these. 

vSphere CLI commands. These can be executed by enabling SSH on ESX host and connecting via Putty

List VIBs (Matching “QLC”)

esxcli software vib list | grep QLC

List VIBs (All)

esxcli software vib list

List VIBs (Network) (Check you don’t disconnect yourself)

esxcli network nic list

Remove VIBs (example scsi-mtip32xx-scsi)

esxcli software vib remove -n scsi-mtip32xx-scsi

Host Maintenance Mode

esxcli system maintenanceMode set --enable true

Host Reboot (Needs to be in maintenance mode)

esxcli system shutdown reboot --reason Upgrades

Notes: The vSphere CLI has been superseded by PowerCLI. PowerCLI is distributed as a Windows PowerShell snapin (PowerCLI 6.0 introduced PowerShell module), and includes over 500 PowerShell cmdlets for managing and automating vSphere and vCloud, along with documentation and samples. 

Reference: https://docs.vmware.com/en/VMware-vSphere/5.5/com.vmware.vsphere.upgrade.doc/GUID-7FFEBD91-5D82-4E32-93AB-F10D8BFFECAA.html

SQL Firewall Rules | PowerShell

Add Windows Firewall exclusions for Microsoft SQL using PowerShell

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
#Enabling SQL Server Ports
New-NetFirewallRule -DisplayName “SQL Server” -Direction Inbound –Protocol TCP –LocalPort 1433 -Action allow
New-NetFirewallRule -DisplayName “SQL Admin Connection” -Direction Inbound –Protocol TCP –LocalPort 1434 -Action allow
New-NetFirewallRule -DisplayName “SQL Database Management” -Direction Inbound –Protocol UDP –LocalPort 1434 -Action allow
New-NetFirewallRule -DisplayName “SQL Service Broker” -Direction Inbound –Protocol TCP –LocalPort 4022 -Action allow
New-NetFirewallRule -DisplayName “SQL Debugger/RPC” -Direction Inbound –Protocol TCP –LocalPort 135 -Action allow
#Enabling SQL Analysis Ports
New-NetFirewallRule -DisplayName “SQL Analysis Services” -Direction Inbound –Protocol TCP –LocalPort 2383 -Action allow
New-NetFirewallRule -DisplayName “SQL Browser” -Direction Inbound –Protocol TCP –LocalPort 2382 -Action allow
#Enabling Misc. Applications
New-NetFirewallRule -DisplayName “HTTP” -Direction Inbound –Protocol TCP –LocalPort 80 -Action allow
New-NetFirewallRule -DisplayName “SSL” -Direction Inbound –Protocol TCP –LocalPort 443 -Action allow
New-NetFirewallRule -DisplayName “SQL Server Browse Button Service” -Direction Inbound –Protocol UDP –LocalPort 1433 -Action allow
#Enable Windows Firewall
Set-NetFirewallProfile -DefaultInboundAction Block -DefaultOutboundAction Allow -NotifyOnListen True -AllowUnicastResponseToMulticast True

Windows Server 2016 | Remove WSUS (Completely)

Trying to completely remove WSUS isn’t as straight forward as uninstalling the role.
These steps are based on WSUS using the WID database (Not SQL)

In Summary:

  • Remove Windows Update Servers (WSUS) role & Windows Internal Database (WID)
  • Remove WSUS cache & Update Services directories
  • Remove WSUS website in IIS
  • Reboot

PowerShell:

Uninstall-WindowsFeature -Name UpdateServices,Windows-Internal-Database
Remove-Item –path D:\WSUS, C:\Windows\WID –recurse
Remove-Item –path C:\Users\MSSQL$MICROSOFT##WID
Remove-Item –path C:\Scripts, C:\Temp –recurse

Remove-Item –path C:\Program Files\Update Services –recurse 

Remove-WebSite -Name "WSUS Administration"
Restart-Computer

References: ServerFault

Windows Commands | Powershell

A few random PowerShell commands in Windows to help complete tasks:

Create New AD User:

New-ADUser -SamAccountName U1 -Name "User 1" -AccountPassword (ConvertToSecureString -AsPlainText "p@ssw0rd" -Force) -Enabled $true -Path 'OU=Test,DC=FABRIKAM,DC=COM'

Displays if “Desktop Experience” is installed:

Get-WindowsFeature *Desktop*

Installs “Desktop Experience” Feature:

Add-WindowsFeature Desktop-Experience

Remove Windows Patches

wusa /uninstall /kb:2952664

Clear all log entries
Although previous logs in event viewer can be helpful for diagnostics, I find old errors sometime cloud the current issues. In order to quickly clear all evertvwr logs entries you can use the following powershell command

wevtutil el | Foreach-Object {Write-Host "Clearing $_"; wevtutil cl "$_"}

Bypass code Execution

Usually if you get this error “PowerShell says “execution of scripts is disabled on this system.” the quick option is to bypass the execution policy:

Set-ExecutionPolicy Unrestricted

List Domain Users using Script | PowerShell

This is custom made code to output all users listed in Active Directory.
This code was rewritten using Powershell in order to make the output more clear and “visually pleasing”

Powershell Option (output to looks like this):

To use:

  1. Paste into notepad.
  2. Save as “DomainMembers.ps1”
  3. Run with Powershell (no progress will be displayed)
  4. Data result will be output to “DomainMembers.txt” located in the C:\DomainMembers.txt This can be specified under the varible ‘$path = “C:\DomainMember.txt”‘

Note:Sometimes the script will not run correctly and the following will be displayed:
“File cannot be loaded because the execution of scripts is disabled on this system”
This security can be removed using the following command.

Set-ExecutionPolicy Unrestricted -Force

Continue reading

Exchange 2010 | OWA Blank page (“HTTP 500” error)

Scenario: OWA web address shows login prompt and the user is able to logon, but a blank page or “HTTP 500” error displays once logged in. The page may also be blank depending on browser settings and if “show friendly URLs” is selected.

Even after a “IISReset /NoForce” or Server reboot, the problem is not fixed.

Cause: Looks like this problem is related to the “Microsoft Exchange Forms-Based Authentifcation Service” not being started or failed to start. This service can just be started from “services.msc”

net start MSExchangeFBA

Note: a number of posts state this problem is related to not having the”RPC over HTTP Proxy” role installed. However in my case the server had been working successfully.

If you have a new migration or build of Exchange 2010 then you may need to ensure that all required features are installed on the exchange server:

Open "Powershell" run as administrator<br />
Import-Module ServerManager<br />
Add-WindowsFeature NET-Framework,RSAT-ADDS,Web-Server,Web-Basic-Auth,Web-Windows-Auth,Web-Metabase,Web-Net-Ext,Web-Lgcy-Mgmt-Console,WAS-Process-Model,RSAT-Web-Server,Web-ISAPI-Ext,Web-Digest-Auth,Web-Dyn-Compression,NET-HTTP-Activation,RPC-Over-HTTP-Proxy -Restart<br />

 

BACKUP!

DO A STANDALONE BACKUP NOW!

This is something we all overlook and it makes life so much easier if you have a copy just dumped to a network share!

GPO Backup:

GPO Restore:

DHCP Backup:

 

Forward mail to a Public Folder | EMC PowerShell

This will forward mail to the public folder

Set-Mailbox "NAME.SURNAME" -ForwardingAddress "email@domain.com"
Set-Mailbox "NAME.SURNAME" -ForwardingAddress "email@domain.com" -DeliverToMailboxAndForward $true

Source: Exchangepedia how to forward mail to a public folder.

Exchange 2007 | EMC Powershell

Open “Exchange Management Shell”

Shortcut refs to: (C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe -PSConsoleFile “C:\Program Files\Microsoft\Exchange Server\bin\exshell.psc1” -noexit -command “. ‘C:\Program Files\Microsoft\Exchange Server\bin\Exchange.ps1′”)

If this is not installed, look at the following article for installing Exchange: http://technet.microsoft.com/en-us/library/bb123694(EXCHG.80).aspx

Don’t get the Exchange Management Shell & Windows Powershell mixed up – for Windows Powershell see:


Adding send as permissions to mailbox:

Add-ADPermission "Mailbox" -User "Domain\User" -Extendedrights "Send As"

Adding full access permissions to mailbox:

Add-MailboxPermission "Mailbox" -User "Trusted User" -AccessRights FullAccess

Adding full access permissions to ALL mailboxes:

Get-Mailboxdatabase | Add-AdPermission -User "Username" -AccessRights GenericAll

List all mailbox stores in size order:

Get-MailboxStatistics | Sort-Object TotalItemSize -Descending | ft DisplayName,@{label="TotalItemSize(MB)";expression={$_.TotalItemSize.Value.ToMB()}},ItemCount

List all mailbox stores in size order (Export to CSV / on Desktop):

Get-MailboxStatistics -Database “Mailbox Database” | Select DisplayName, LastLoggedOnUserAccount, ItemCount, TotalItemSize, LastLogonTime, LastLogoffTime | Export-CSV test.csv

List all mailbox stores in size order:

Get-MailboxStatistics -Database “Mailbox Database” | Sort -Property TotalItemsize | Format-Table DisplayName, LastLoggedOnUserAccount, ItemCount, @{expression={$_.totalitemsize.value.ToMB()};label=”Size(MB)”}, LastLogonTime, LastLogoffTime

Purge all disconnected mailboxes:

(Add all the disconnected mailboxes into a var by typing the below:)

$users = Get-MailboxStatistics | where-object { $_.DisconnectDate -ne $null } | Select DisplayName,MailboxGuid,Database

Purge all the disconnected mailboxes in the previously made var by typing the below:

$users | ForEach { Remove-Mailbox -Database $_.Database -StoreMailboxIdentity $_.MailboxGuid -confirm:$false }

List all Public folder email addresses (output to file) 

I had a request for all the email addresses associated to public mailboxes, as these are not displayed on the client in Outlook.

Method1:

Displays a list of Public Folders & Email addresses output to TXT File (FL = Formats list with full text)

Get-PublicFolder -Recurse | Get-MailPublicFolder | fl DisplayName,Emailaddresses &gt; c:\publicfolders_list.txt

Method2: Displays a list of Public Folders & Email addresses output to CSV File:

# Export-CSV PowerShell Spreadsheet
Clear-Host
$FilePath = "c:\publicfolders.csv"
Get-MailPublicFolder | Select-Object DisplayName -expand emailaddresses| Export-CSV $FilePath

List Exchange 2007 Product Version

Get-ExchangeServer | fl name,edition,admindisplayversion

List Exchange 2007 Database Size

Get-MailboxDatabase | foreach-object {add-member -inputobject $_ -membertype noteproperty -name mailboxdbsizeinGB -value ([math]::Round(([int64](get-wmiobject cim_datafile -computername $_.server -filter ('name=''' + $_.edbfilepath.pathname.replace("\","\\") + '''')).filesize / 1GB),2)) -passthru} | Sort-Object mailboxdbsizeinGB -Descending | format-table identity,mailboxdbsizeinGB

List Exchange 2007 GUID

Get-MailboxDatabase -Identity "&lt;server name&gt;\&lt;storage group name&gt;\&lt;database name&gt;" | Format-Table Name, GUID

Public Folder Permissions via Powershell

Type the below, replacing ‘public folder name’ with your public folder name/path and you must keep the \ at the front of it and also replace ‘username’ with the username:

Add-PublicFolderClientPermission -Identity "\public folder name" -AccessRights Owner -User username

Owner can be replaced with the following roles:

  • None
  • Owner
  • PublishingEditor
  • Editor
  • PublishingAuthor
  • Author
  • Non-Editing Author
  • Reviewer
  • Contributor

Source: http://technet.microsoft.com/en-us/library/bb310789(EXCHG.80).aspx


Finding a Mailbox via Powershell

Get-Mailbox -identity findmyemail@mydomain.com

List Members of a Distribution List (output on screen)

Get-DistributionGroupMember-identity "staff.technical"

List Members of a Distribution List including their primary email address and formatted (output to CSV on C:\)

Get-DistributionGroupMember –identity “staff.technical” | ft name, primarysmtpaddress &gt; c:\members.csv

List Members of a Dynamic Distribution List

$group = Get-DynamicDistributionGroup –identity “AllStaff-DL”
Get-Recipient –RecipientPreviewFilter $group.RecipientFilter | sort name | select name &gt; C:\dlist_members.txt

Continue reading