Programming:Windows PowerShell

From WhyAskWhy.org Wiki
Revision as of 15:31, 9 June 2016 by Deoren (talk | contribs) (Added example of copying all users in one AD group to another AD group)
Jump to: navigation, search


SQL Server

List enabled SQL Server Agent jobs

# Load required assembly
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null

# Create new object/connection
$sqlsvr = New-Object ('Microsoft.SqlServer.Management.Smo.Server') "LOCALHOST"

# Examine object
$sqlsvr.JobServer.Jobs | Where-Object {$_.IsEnabled -eq $FALSE} | Select Name,LastRunOutcome,LastRunDate

Active Directory

Look up Active Directory group members

I found this tip on ServerFault.com.

Import-Module ActiveDirectory
Get-ADGroupMember "MyADGroupName" | Select-Object name | Sort-Object name

If you wish to expand all group members from any included groups, run the command like so:

Import-Module ActiveDirectory
Get-ADGroupMember "MyADGroupName" -recursive | Select-Object name | Sort-Object name

and if you wish to instead list by Distinguished Name use this:

Import-Module ActiveDirectory
Get-ADGroupMember "MyADGroupName" -recursive | Select-Object distinguishedName | Sort-Object distinguishedName

An alternate approach is to use dsquery and dsget from the Remote Server Administration Tools (RSAT) package:

dsquery group -name "MyADGroupName" | dsget group -members -expand

With the current set of options the list of users will be by Distinguished Name.

Look up group memberships for user account

Import-Module ActiveDirectory
Get-ADPrincipalGroupMembership username | select name
name
----
Domain Users
Domain Computers
Workstation Admins
Company Users
Company Developers
AutomatedProcessingTeam

Copy all users in one group to another group

AFAIK, both groups have to be created in advance.

Import-Module ActiveDirectory
Get-ADGroupMember -Identity GROUP-A | Add-ADPrincipalGroupMembership -MemberOf GROUP-B


General

Leave out column headers in output

Here is an example of querying the Services list, limiting the results to 10 items and then sorting them, all as raw values:

Get-Service | Select-Object -First 10 -ExpandProperty DisplayName | sort

This gives a bare list like so:

ActiveX Installer (AxInstSV)
Adobe Acrobat Update Service
Application Experience
Application Identity
Application Information
Application Layer Gateway Service
Application Management
ASP.NET State Service
Windows Audio
Windows Audio Endpoint Builder


Links