Showing posts with label PowerShell v3. Show all posts
Showing posts with label PowerShell v3. Show all posts

Wednesday, August 23, 2017

Invoke-O365AzureSync.ps1

Today's script is for those who manage AzureSync and looking for a quick way to kick off Full or Delta syncs without having to RDP to the server and execute script.

Pretty straight forward script and lots of comments / verbose messages.  Unless requested will not be providing a code break out post.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<#
.SYNOPSIS
    Run Azure (DirSync) on dedicated remote server
.DESCRIPTION
    Run Azure (DirSync) on dedicated remote server
.PARAMETER Type
    Type of Sync to complete

    o Delta - Changes only
    o Full - Complete re-sync
.PARAMETER ADSyncPath
    Enter path for ADSync modeule if different then default
.PARAMETER Server
    Target server that has Azure Sync installed
.EXAMPLE
    Execute a full Azure Sync
    
    Invoke-O365AzureSync.ps1 -Server server -Type Full
.EXAMPLE
    Execute a change only Azure Sync
    
    Invoke-O365AzureSync.ps1 -Server server -Type Delta
.NOTES
    Created by Chris Lee
    Date September 6, 2016
.LINK  
    GitHub: https://github.com/clee1107/Public/blob/master/O365/Invoke-O365AzureSync.ps1
    Blogger:http://www.myitresourcebook.com/2017/08/invoke-o365azuresyncps1.html
 
#>

[Cmdletbinding()]
Param
(
    [string]
    [Parameter(Mandatory=$true)]
    [ValidateSet('Delta','Full')]
    $type,
    [string]
    $ADSyncPath= 'C:\Program Files\Microsoft Azure AD Sync\Bin\ADSync\ADSync.psd1',
    [string]
    $Server
)

#################################
## DO NOT EDIT BELOW THIS LINE ##
#################################

## region Functions
    Function Test-Verbose
        {
            [cmdletbinding()]
            Param()
            Write-Verbose "Verbose output"
            "Regular output"
        }
    Test-Verbose
## endregion

#################################
## DO NOT EDIT BELOW THIS LINE ##
#################################

## Connect to remote server
    Write-Verbose -Message "Opening PSSession to $Server"
    $Session = New-PSSession -ComputerName $Server
## Check that ADSync is present at supplied path
    Write-Verbose -Message "Checking for ADSync.psd1 at $ADSyncPath"
    If (Invoke-command -Session $Session -ArgumentList $ADSyncPath -scriptblock { param ($ADSyncPath) Test-Path $ADSyncPath})
        {
            Write-Verbose -Message "ADSync Module found"
            Invoke-Command -Session $Session -ArgumentList $ADSyncPath -scriptblock { param ($ADSyncPath) Import-Module $ADSyncPath}
            Write-Verbose -Message "ADSync Module Loaded"
            ## Check if request for Delta Sync otherwise (else) execute full
                If ($type -eq "Delta")
                    {
                        Write-Verbose -Message "Executing Change Only (Delta) Sync"
                        Invoke-Command -Session $Session {Start-ADSyncSyncCycle -PolicyType Delta}
                    }
                Else
                    {
                        Write-Verbose -Message "Executing Full Sync"
                        Invoke-Command -Session $Session {Start-ADSyncSyncCycle -PolicyType Initial}
                    }
        }
    Else
        {
            Verbose-Error "Unable to locate ADSync.psd1 at $ADSyncPath"
        }
## Close and Remove the remote session
    Write-Verbose -Message "Removing PSSession to $Server"
    Remove-PSSession $Session


Full script can be accessed from following link:
https://github.com/clee1107/Public/blob/master/O365/Invoke-O365AzureSync.ps1
Further reference links for PowerShell cmdlets used can be found on following post:

Code Snippets created via: http://hilite.me/


Wednesday, August 16, 2017

Remove-O365PSSession.ps1

Today's script does some basic house cleaning when closing Office 365 Sessions.

As script is simple now code break down unless I receive requests.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<#
.SYNOPSIS
    Remove open O365 PSSessions
.DESCRIPTION
    Remove open O365 PSSessions
.EXAMPLE
    Remove-O365PSSession.ps1
.NOTES
    Created by Chris Lee
    Date April 20, 2017
.LINK 
    GitHub: https://github.com/clee1107/Public/blob/master/O365/Remove-O365PSSession.ps1
    Blogger:http://www.myitresourcebook.com/2017/08/httpsgithubcomclee1107publicblobmastero.html
#>

#################################
## DO NOT EDIT BELOW THIS LINE ##
#################################

##Close open All O365 product Sessions
Write-Verbose -Message "Removing all PSSessions"
Get-PSSession | Remove-PSSession
Write-Verbose -Message "Disconnecting SharePoint Online"
$ExitPowershell = Read-Host -Prompt "Disconnect from O365 (Will close current Powershell Window) [Y]/N"
If ($ExitPowershell -eq "Y" -OR $ExitPowershell -eq $null -OR $ExitPowershell -eq "")
    {
        stop-process -Id $PID
    }


Full script can be accessed from following link:
https://github.com/clee1107/Public/blob/master/O365/Remove-O365PSSession.ps1
Further reference links for PowerShell cmdlets used can be found on following post:

Code Snippets created via: http://hilite.me/

Wednesday, August 9, 2017

New-O365PSSession.ps1

Today's script can be used with previous Set-O365EncryptedCredentials or standalone.

Scope of script is following:

  • Checks for stale O365 Sessions and closes them
  • Will use saved credentials (Set-O365EncryptedCredentials.PS1) or prompt for user to provide
  • Will fail if MSOnline Module not installed
  • Will Skip SharePoint / Skype if required modules not installed
Due to length of script unless requested will not be doing code break down.


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
<#
.SYNOPSIS
    Connect to O365
.DESCRIPTION
    Connect to O365
        If Encrypeted path available will use that otherwise prompts for credentials.
.PARAMETER SkipSharePoint
    If no DNS for SharePoint, add this to skip SharePoint options
.PARAMETER SkipSkype
    If no DNS for Lync, add this to skip Lync options
.PARAMETER SkipExchange
    If no DNS for Exchange, add this to skip Exchange options
.PARAMETER SkipSecurity
    If no DNS for Security & Compliance Center, add this to skip Security & Compliance Center options
.PARAMETER Path
    Enter alternate path for ecrypted credential files, defualt is users local app data
.EXAMPLE
    Opens PowerShell Session for all Office365 products
    
    New-O365PSSession.ps1
.EXAMPLE
    Opens PowerShell Session for all Office365 products except Exchange online
    
    New-O365PSSession.ps1 -skipExchange
.NOTES
    Created by Chris Lee
    Date April 20, 2017

    Some code pulled from:
        PoShConnectToOffice365.ps1
        Created by DJacobs for HBS.NET
.LINK
    GitHub: https://github.com/clee1107/Public/blob/master/O365/New-O365PSSession.ps1
    Blogger:http://www.myitresourcebook.com/2017/08/new-o365pssessionps1.html
#>

[Cmdletbinding()]
Param
(
    [switch]
    $SkipSharePoint,
    [switch]
    $SkipSkype,
    [switch]
    $SkipExchange,
    [switch]
    $SkipSecurity,
    [String]
    $Path = [Environment]::GetFolderPath("LocalApplicationData")
)

#################################
## DO NOT EDIT BELOW THIS LINE ##
#################################

## region Functions
    Function Test-Verbose
        {
            [cmdletbinding()]
            Param()
            Write-Verbose "Verbose output"
            "Regular output"
        }
    Test-Verbose
## endregion

## Check for Credential Files present
    ##Check for User file
        Write-Verbose -Message "Checking for optional user file"
        IF (!(Test-Path -Path "$Path\O365user.txt"))
            {
                $AdminName = Read-Host -Prompt "Enter your tenant UPN"       
            }
        else
            {
                Write-Host -ForegroundColor Green "User File found"
                $AdminName = Get-Content "$Path\O365user.txt"
            }
    ##Load Encrypted password file
        Write-Verbose -Message "Checking for required password file"
        IF (!(Test-Path -Path "$Path\O365cred.txt"))
            {
                $Pass = Read-Host -Prompt "Enter your tenant password" -AsSecureString `
                    | ConvertFrom-SecureString
            }
        else
            {
                Write-Host -ForegroundColor Green "Password File Found"
                $Pass = Get-Content "$Path\O365cred.txt" | ConvertTo-SecureString
            }
## Create Cred variable
    Write-Verbose -Message "Creating Credential varialble from files"
    $Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $AdminName, $Pass

## Check for O365 Component Modules
    ## MSOnline (AzureAD)
        Try 
            {
                Write-Verbose -Message "$(Get-Date -f o) Importing Module MSOline"
                Import-Module MSOnline -DisableNameChecking -ErrorAction Stop
            }
        Catch 
            {
                Write-Verbose -Message "MSOnline Module not found."
                Throw  "MSOnline Module not found. Must install to continue.  Can be installed via PowerShell script: Install-O365Modules.PS1"
            }
    ## SharePoint Online
        Try 
            {
                Write-Verbose -Message "$(Get-Date -f o) Importing SharePoint Module"
                Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking -ErrorAction Stop
            }
        Catch 
            {
                Write-Verbose -Message "SharePoint Online Module not found."
                Write-Error  "SharePoint Online Module not found, will be skiped.  Can be installed via PowerShell script: Install-O365Modules.PS1"
                $SkipSharePoint = $True
            }
    ## Skype for Business
        Try 
            {
                Write-Verbose -Message "$(Get-Date -f o) Importing Skype for Business Module"
                Import-Module SkypeOnlineConnector -DisableNameChecking -ErrorAction Stop
            }
        Catch 
            {
                Write-Verbose -Message "Skype for Business Module not found."
                Write-Error  "Skype for Business Module not found, will be skiped.  Can be installed via PowerShell script: Install-O365Modules.PS1"
                $SkipSkype = $True
            }


## Connect of O365 with error checks
    ##Connect MSOnline (Azure Active Directory)
        Write-Verbose -Message "Connecting MSOnline (Office 365)"
        ## Office 365
            Try #Check if already connected to MSOnline
                {
                    Write-Verbose -Message "Checking if already connected to MSOnline (Azure Active Directory)"
                    Get-MsolDomain -ErrorAction Stop > $null
                    Write-Host -ForegroundColor Green "Already Connected to MSOnline (Azure Active Directory)"
                }
            Catch #Connect to MSOline
                {
                    Try #Try to connect to MSOnline
                        {
                            Write-Verbose -Message "Connecting MsolService"
                            Connect-MsolService -Credential $cred -ErrorAction Stop
                            Get-MsolDomain -ErrorAction Stop > $null
                            Write-Host -ForegroundColor Green "Connected to MSOnline (Azure Active Directory)"
                        }
                    Catch [Microsoft.Online.Administration.Automation.MicrosoftOnlineException] #Failed to connect bad credentials
                        {
                            Write-Error -Message "Error. Failed to Connect to MsolService because bad username or password." -ErrorAction Stop
                        }
                    Catch #Failed to connect other then credential issue
                        {
                            #$_ | fl * -Force
                            Write-Error -Message "Error. Failed to connect to MsolService because $_" -ErrorAction Stop
                        }
                    if ($ShowProgress) #Present MSOL Domains connected to
                        {
                            Write-Verbose -Message "$(Get-Date -f o) Listing MSOL Domains"
                            Get-MsolDomain | ft -AutoSize
                        }
                }

            
    ##Connect SharePoint Online
        Write-Verbose -Message "Connecting SharePoint Online"
        ##SharePoint
            if (-not $SkipSharePoint)
                {
                    Try #Check if already connected to Sharepoint Online
                        {
                            Write-Verbose -Message "Checking if already connected to SharePoint Online"
                            Get-SPOsite -ErrorAction Stop > $null
                            Write-Host -ForegroundColor Green "Already Connected to SharePoint Online"
                        }
                    Catch #Connect to SharePoint Online
                        {
                            Write-Verbose -Message "Not connected to SharePoint Online"
                            Try 
                                {
                                    Write-Verbose -Message "$(Get-Date -f o) Connecting SP Online Service"
                                    Connect-SPOService -Url https://$spAdminName-admin.sharepoint.com -Credential $cred -ErrorAction Stop
                                    Get-SPOSite -ErrorAction Stop > $null
                                    Write-Host -ForegroundColor Green "Connected to SharePoint Online"
                                }
                            Catch 
                                {
                                    Write-Error -Message "Error. Cannot connect to 'SPOService' because $_" -ErrorAction Stop
                                }
                            if ($ShowProgress) 
                                {
                                    Write-Verbose -Message "$(Get-Date -f o) Listing SP Online Sites"
                                    Get-SPOSite | ft -AutoSize
                                } 
                        }
                    
                } 
            else   
                {
                    Write-Verbose -Message "Skipping SharePoint"
                }
    ##Connect Skype for Business
        Write-Verbose -Message "Connecting Skype for Business"
        if (-not $SkipSkype) 
            {   
                Try 
                    {
                        Write-Verbose -Message "Checking if already connected to Skype for Business"
                        If ((Get-PSSession | Where-Object {$_.ComputerName -like "admin1a*" -AND $_.State -like "Opened"}))
                            {
                                Write-Host -ForegroundColor Green "Already Connected to Skype for Business"
                                Write-Verbose -Message "Removing broken PSSessions for Skype for Business"
                                $PSSessionIDs = Get-PSSession `
                                    | Where-Object {$_.ComputerName -like "admin1a*" -AND $_.State -notlike "Opened"} `
                                    | Select-Object Id
                                If ($PSSessionIDs -eq $null -OR $PSSessionIDs -eq "")
                                    {
                                        Write-Verbose -Message "No broken sessions to remove"
                                    }
                                else 
                                    {
                                        Foreach ($PSessionID in $PSSessionIDs)
                                            {Remove-PSSession $PSessionID}
                                        Write-Verbose -Message "All broken Skype for Business sessions removed"
                                    }
                            }
                    }
                Catch 
                    {
                        Try 
                            {
                                Write-Verbose -Message "$(Get-Date -f o) Creating Skype for Business Session"
                                $skypeSession = New-CsOnlineSession -Credential $cred -ErrorAction Stop
                            }
                        Catch 
                            {
                                Write-Warning "$(Get-Date -f o) Error. Cannot connect to Skype for Business because $_"
                            }
                        Try 
                            {
                                Write-Verbose -Message "$(Get-Date -f o) Importing PSSession for Skype for Business"
                                $null = Import-PSSession $skypeSession -AllowClobber -ErrorAction Stop
                                Write-Verbose -Message "Successfully imported PSSession for Skype for Business."
                            }
                        Catch 
                            {
                                Write-Error -Message "Failed to import PSSession for Skype for Business." -ErrorAction Continue
                            }
                    }
                if ($ShowProgress) 
                    {
                        if (Get-Command -Name Get-CsMeetingConfiguration -ErrorAction SilentlyContinue) 
                            {
                                Write-Verbose -Message "Successfully connected to Skype for Business."
                            } 
                        else 
                            {
                                Write-Warning -Message "Error. Did not connect to Skype for Business."
                            }
                    }
                If ((Get-PSSession | Where-Object {$_.ComputerName -like "admin1a*" -AND $_.State -like "Opened"}))
                    {
                        Write-Host -ForegroundColor Green "Connected to Skype for Business"
                    }
                else 
                    {
                        Write-Host -ForegroundColor Red "Failed to connect to Skype for Business"
                    }
            } 
        else 
            {
                Write-Verbose -Message "Skipping Skype for Business"
            }
     
    ##Connect Exchange Online
        Write-Verbose -Message "Connecting Exchange Online"
        #$Exchange
            if (-not $SkipExchange) 
                {
                    Write-Verbose -Message "Checking if already connected to Exchange Online"
                    If ((Get-PSSession | Where-Object {$_.ComputerName -like "outlook*" -AND $_.State -like "Opened"}))
                        {
                            Write-Host -ForegroundColor Green "Already Connected to Exchange Online"
                            Write-Verbose -Message "Removing broken PSSessions for Exchange"
                            $PSSessionIDs = Get-PSSession `
                                | Where-Object {$_.ComputerName -like "outlook*" -AND $_.State -notlike "Opened"} `
                                | Select-Object Id
                            If ($PSSessionIDs -eq $null -OR $PSSessionIDs -eq "")
                                {
                                    Write-Verbose -Message "No broken sessions to remove"
                                }
                            else 
                                {
                                    Foreach ($PSessionID in $PSSessionIDs)
                                        {Remove-PSSession $PSessionID}
                                    Write-Verbose -Message "All broken Exchange sessions removed"
                                }
                        }
                    else 
                        {
                            Try
                                {
                                    Write-Verbose -Message "$(Get-Date -f o) Creating Exchange Session"
                                    $exchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange `
                                        -ConnectionUri "https://outlook.office365.com/powershell-liveid/" `
                                        -Credential $cred `
                                        -Authentication "Basic" `
                                        -AllowRedirection `
                                        -ErrorAction Stop
                                    Write-Verbose -Message "Successfully created Exchange Session."      
                                }
                            Catch 
                                {
                                    Write-Error -Message "Error. Cannot talk to Exchange because $_" -ErrorAction Stop
                                }
                            Try 
                                {
                                    Write-Verbose -Message "$(Get-Date -f o) Importing PSSession for Exchange"
                                    $null = Import-PSSession $exchangeSession -AllowClobber -ErrorAction Stop -DisableNameChecking
                                    Write-Verbose -Message "Imported PSSession for Exchange."
                                }
                            Catch 
                                {
                                    Write-Error -Message "Error. Cannot Import PSSession for Exchange because $_" -ErrorAction Stop
                                }
                            if ($ShowProgress) 
                                {
                                    Write-Verbose -Message "$(Get-Date -f o) Listing Accepted Domains"
                                    Get-AcceptedDomain | Format-Table -Property DomainName, DomainType, IsValid -AutoSize
                                }
                            If ((Get-PSSession | Where-Object {$_.ComputerName -like "outlook*" -AND $_.State -like "Opened"}))
                                {
                                    Write-Host -ForegroundColor Green "Connected to Exchange"
                                }
                            else 
                                {
                                    Write-Host -ForegroundColor Red "Failed to connect to Exchange"
                                }
                        }
                }
            else 
                {
                    Write-Verbose -Message "Skipping Exchange"
                }
    ##Connect Security & Compliance Center
        Write-Verbose -Message "Connecting Security & Compliance Center"
        #$Exchange
            if (-not $SkipSecurity) 
                {
                    If ((Get-PSSession | Where-Object {$_.ComputerName -like "*compliance.protection.outlook*" -AND $_.State -like "Opened"}))
                        {
                            Write-Host -ForegroundColor Green "Already Connected to Security & Compliance Center Online"
                            Write-Verbose -Message "Removing broken PSSessions for Security & Compliance Center"
                            $PSSessionIDs = Get-PSSession `
                                | Where-Object {$_.ComputerName -like "*compliance.protection.outlook*" -AND $_.State -notlike "Opened"} `
                                | Select-Object Id
                            If ($PSSessionIDs -eq $null -OR $PSSessionIDs -eq "")
                                {
                                    Write-Verbose -Message "No broken sessions to remove"
                                }
                            else 
                                {
                                    Foreach ($PSessionID in $PSSessionIDs)
                                        {Remove-PSSession $PSessionID}
                                    Write-Verbose -Message "All broken Exchange sessions removed"
                                }
                        }
                    else 
                        {
                             Try 
                                {
                                    Write-Verbose -Message "$(Get-Date -f o) Creating Security & Compliance Center Session"
                                    $securitySession = New-PSSession -ConfigurationName Microsoft.Exchange `
                                        -ConnectionUri "https://ps.compliance.protection.outlook.com/powershell-liveid/" `
                                        -Credential $cred `
                                        -Authentication "Basic" `
                                        -AllowRedirection `
                                        -ErrorAction Stop
                                        Write-Verbose -Message "Successfully created Exchange Security & Compliance Session."      
                                }
                            Catch 
                                {
                                    Write-Error -Message "Error. Cannot talk to Exchange Security & Compliance because $_" -ErrorAction Stop
                                }
                            Try 
                                {
                                    Write-Verbose -Message "$(Get-Date -f o) Importing PSSession for Security & Compliance Center"
                                    $securitySession = Import-PSSession $securitySession -Prefix cc -AllowClobber -ErrorAction Stop -DisableNameChecking
                                }
                            Catch 
                                {
                                    Write-Warning "Error. Cannot Import PSSession for Security & Compliance Center because $_"
                                }                    
                            if ($ShowProgress) 
                                {
                                    if (Get-Command -Name Get-CsMeetingConfiguration -ErrorAction SilentlyContinue) 
                                        {
                                            Write-Verbose -Message "Successfully connected to Security & Compliance Center."
                                        } 
                                    else 
                                        {
                                            Write-Warning -Message "Error. Did not connect to Security & Compliance Center."
                                        }
                                }
                            If ((Get-PSSession | Where-Object {$_.ComputerName -like "*compliance.protection.outlook*" -AND $_.State -like "Opened"}))
                                {
                                    Write-Host -ForegroundColor Green "Connected to Security & Compliance Center"
                                }
                            else 
                                {
                                    Write-Host -ForegroundColor Red "Failed to connect to Security & Compliance Center"
                                }
                        }
                    
                } 
            else 
                {
                    Write-Verbose -Message "Skipping Security & Compliance Center"
                }


Full script can be accessed from following link:
https://github.com/clee1107/Public/blob/master/O365/New-O365PSSession.ps1
Further reference links for PowerShell cmdlets used can be found on following post:

Code Snippets created via: http://hilite.me/

Wednesday, August 2, 2017

Install-O365Modules.ps1

Today's post is aimed at setting up your system to connect to all the components of O365.

I feel this script is pretty straight forward and self explaining. If receive requests will come back and do a more in depth post on what is happening.


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
<#
.SYNOPSIS
    Check for O365 components are present and attempt to install or direct to installers.
.DESCRIPTION
    Check for O365 components are present and attempt to install or direct to installers.
    Installs missing modules for:  
        o Active Directory Online
        o Skype for Business Online
        o SharePointOnline
.EXAMPLE
    Standard execution
    
    Install-O365Modules.ps1
.EXAMPLE
    Verbose messages for troubleshooting installation
    
    Install-O365Modules.ps1 -Verbose
.NOTES
    Created by Chris Lee
    Date April 20, 2017

    Some code pulled from:
        PoShConnectToOffice365.ps1
        Created by DJacobs for HBS.NET
.LINK
    GitHub: https://github.com/clee1107/Public/blob/master/O365/Install-O365Modules.ps1
    Blogger: http://www.myitresourcebook.com/2017/08/install-o365modulesps1.html

#>

[Cmdletbinding()]
Param
(
)

#################################
## DO NOT EDIT BELOW THIS LINE ##
#################################

## Install O365 Components
    ##Install MSOnline (Azure Active Directory)
        Write-Verbose -Message "Checking for MSOnline (Office 365) Module"
        ## Office 365
            Try 
                {
                    Write-Verbose -Message "Not connected to MSOnline (Azure Active Directory)"
                    Write-Verbose -Message "$(Get-Date -f o) Importing Module MSOline"
                    Import-Module MSOnline -DisableNameChecking -ErrorAction Stop
                }
            Catch 
                {
                    Write-Verbose -Message "MSOnline Module not found."
                    Write-Verbose -Message 'Check if PowerShell session running in "run as administrator"'
                    If (((whoami /all | select-string S-1-16-12288) -ne $null) -eq $false)
                        {
                            Write-Error 'PowerShell must be ran in "run as administrator to install MSOnline module"'
                            Exit
                        }
                    else 
                        {
                            Write-Host -ForegroundColor Yellow "Installing MSOnline Module"
                            Install-Module MSOnline
                            Try 
                                {
                                    Write-Verbose -Message "$(Get-Date -f o) Importing Module MSOline"
                                    Import-Module MSOnline -DisableNameChecking -ErrorAction Stop
                                }
                            Catch 
                                {
                                    Write-Error -Message "Error. Cannot import module 'MSOnline' because $_" -ErrorAction Stop
                                }
                        }
                    }
            
    ##Install SharePoint Online
        Write-Verbose -Message "Checking for SharePoint Online Module"
        ##SharePoint
                    Try 
                        {                   
                            Write-Verbose -Message "$(Get-Date -f o) Importing SharePoint Module"
                            Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking -ErrorAction Stop
                        }
                    Catch 
                        {
                            Write-Verbose -Message "SharePoint Online Module not found."
                            $temp = Read-Host "Launch browser to download SharePoint Online Management Shell? [Y]/N"
                            If ($temp -eq $null -OR $temp -eq "" -OR $temp -eq "Y")
                                {
                                    Start-Process https://www.microsoft.com/en-us/download/details.aspx?id=35588      
                                }
                            Else
                                {
                                    Write-Error -Message "Error. Failed to import the module 'Microsoft.Online.SharePoint.PowerShell' because $_" -ErrorAction Stop
                                }
                        }
                        
    ##Install Skype for Business
        Write-Verbose -Message "Checking for Skype for Business Module"
        Try 
            {
                Write-Verbose -Message "$(Get-Date -f o) Importing Module Skype for Business Online Connector"
                Import-Module SkypeOnlineConnector -DisableNameChecking -ErrorAction Stop
            }
        Catch 
            {
                Write-Verbose -Message "SkypeOnlineConnector Module not found."
                $temp = Read-Host "Launch browser to download Skype for Business Online, Windows PowerShell Module? [Y]/N"
                    If ($temp -eq $null -OR $temp -eq "" -OR $temp -eq "Y")
                        {
                            Start-Process https://www.microsoft.com/en-us/download/details.aspx?id=39366    
                        }
                    Else
                        {
                            Write-Error -Message "Error. Failed to import the module 'SkypeOnlineConnector' because $_" -ErrorAction Stop
                        }
            }

Full script can be accessed from following link:
https://github.com/clee1107/Public/blob/master/O365/Install-O365Modules.ps1
Further reference links for PowerShell cmdlets used can be found on following post:

Code Snippets created via: http://hilite.me/

Monday, January 20, 2014

Microsoft Virtual Academy: PowerShell M08


To start your own learning check out Microsoft Virtual Academy:
(http://www.microsoftvirtualacademy.com/training-courses/getting-started-with-powershell-3-0-jump-start?o=3276#?fbid=aVs9FfAH2DJ)
(rewritten based on my notes available here: https://drive.google.com/file/d/0B1fwreWrAZioWUlmOXVBYlJEWU0/edit?usp=sharing)

Module 8 "Automation in scale: remoting" consists of 2 video segments totaling ≈ 26 minutes along with a PowerPoint of 9 slides.

Overview:
  • Remoting
  • Sessions
  • Remote CMDLETs
  • Measure execution speed
Remoting

    As covered in past module/posts we can execute CMDLETs on remote systems using the Invoke-Command / ICM.  Somethings to understand about this process.


  • When executed command sent to remote system to establish PowerShell session.
    • Involves creating TCP connection, PowerShell session each time the ICM command is used.
  • This is inefficient for many reasons:
    1. Resources wasted to create and tear down PowerShell session on remote system for each ICM execution
    2. Since each ICM is it's own session nothing remains in memory after tear down.  This causes problems for automation.
To get around the limitations and work more efficiently remote PowerShell sessions are allowed.  It allows the remote start of a PowerShell session that will remain alive until closed. This allows for data to be passed through following CMDLETs.



Sessions

    A PowerShell session allows the execution of CMDLETs and usage of local memory for data/variables.  A session can be created by opening local PowerShell shell or through CMDLET New-PSSession (Sessions can be local or remote).

New-PSSession -Computername [DC1]
     Opens new session with remote system (DC1)

To view current live/open sessions we use the following:
Get-PSSession
 Id       Name            ComputerName    State         ConfigurationName         Availability
 --        ----                  ------------                  -----            -----------------                        ------------
  4       Session4      cutie                        Opened     Microsoft.PowerShell     Available
  5       Cutie             cutie                         Opened     Microsoft.PowerShell     Available


Remote CMDLETS
    
Enabling Remoting


Monday, January 13, 2014

Microsoft Virtual Academy: PowerShell M07 (Part 3)

Here we are module 7 only two more.  This is a short segment but lots of information.  To keep things short I have split it among three posts.  Check the Overview to see what is covered under this post.

To start your own learning check out Microsoft Virtual Academy:
(http://www.microsoftvirtualacademy.com/training-courses/getting-started-with-powershell-3-0-jump-start?o=3276#?fbid=aVs9FfAH2DJ)
(rewritten based on my notes available here: https://drive.google.com/file/d/0B1fwreWrAZioQ28xTmx0d29HUzQ/edit?usp=sharing)

Module 7: "Getting prepared for automation" consists of 2 video segments totaling ≈ 26 minutes along with a PowerPoint of 12 slides.

Overview
Output to Screen

 PowerShell offers a few ways to provide output to the screen from your script.   The most common is Write-Host as it provides the ability to format colors.  There are some issues with using Write-Host as it breaks the ability to pipe.  To maintain the pipeline use Write-Output.  To provide you color text they have provided us with Write-Error / Write-Warning / Write-Debug.

Write-Host
    Allows output to the screen to be formatted.  Remember this breaks pipeline usage and is not best practice in a script.

Write-Host "Hello" -Foregroundcolor red -BackGroundColor green
         Sets colors
   
     Outputs:Hello
   

Write-Output
   Way to output to screen with out breaking pipeline.

Write-Output "Hello"

    Outputs: Hello

Write-Error / Write-Warning / Write-Debug
    All three of these cmdlets use the default PowerShell scheme to maintain quick recognition.

Write-Warning "Help, Help"

    Outputs: Help, Help

Write-Error "Doom, Doom"

     Outputs: Doom, Doom

Check out the rest of this segment:
Part 1: http://cleeit.blogspot.com/2014/01/MVA-powershell-m07-part1.html
Part 2: http://cleeit.blogspot.com/2014/01/MVA-powershell-m07-part2.html

Microsoft Virtual Academy: PowerShell M07 (Part 2)

Here we are module 7 only two more.  This is a short segment but lots of information.  To keep things short I have split it among three posts.  Check the Overview to see what is covered under this post.

To start your own learning check out Microsoft Virtual Academy:
(http://www.microsoftvirtualacademy.com/training-courses/getting-started-with-powershell-3-0-jump-start?o=3276#?fbid=aVs9FfAH2DJ)
(rewritten based on my notes available here: https://drive.google.com/file/d/0B1fwreWrAZioQ28xTmx0d29HUzQ/edit?usp=sharing)

Module 7: "Getting prepared for automation" consists of 2 video segments totaling ≈ 26 minutes along with a PowerPoint of 12 slides.

Overview

Variables

   Variables are a huge part the power o f PowerShell.  Variables can store not just numerical or string for output but also cmdlets for recall later, executed against, or even run method if supported.  A variable is defined by $ and can be recalled by $name.  Variables are not saved after shell or session is closed.  Check out the slides for how to use variables and quotes.

Example of string for output:
$myvar="HelloWorld"
        Sets HelloWorld into variable myvar
$myvar
        To call variable we enter it's name
HelloWorld
        Value returned from call

Example of numerical 
$myvar="1354"
        Sets HelloWorld into variable myvar
$myvar
        To call variable we enter it's name
1354
        Value returned from call

Example of cmdlet:
$myvar=Get-Service bits
        Sets cmdlet Get-Service to variable myvar
$myvar
        Calls variable myvar which executes stored cmdlet Get-Service bits
Status          Name         DisplayName
------          ----         -----------
Running         bits         Background Intelligent Transfer Ser...
        Results of cmdlet

Example of cmdlet executed against:
$myvar=Get-Service bits
        Sets cmdlet Get-Service to variable myvar
$myvar | gm
        Calls variable myvar which executes stored cmdlet Get-Service bits and runs through pipe get-member
                 TypeName: System.ServiceProcess.ServiceController

Name                                                  MemberType                  Definition
----                                                        ----------                            ----------
Name                                                  AliasProperty                 Name = ServiceName
RequiredServices                            AliasProperty                  RequiredServices = ServicesDependedOn
Disposed                                           Event                                System.EventHandler Disposed(System.Object, System.EventArgs)
Close                                                  Method                             void Close()
Continue                                            Method                              void Continue()
....
        Results of cmdlet

Example of cmdlet method:
$myvar=Get-Service bits
        Sets cmdlet Get-Service to variable myvar
$myvar.status
        Calls variable myvar which executes stored cmdlet Get-Service bits but only outputs Status
Running
        Results of cmdlet

  Variables are also not limited to a single word or continues string for a name.  By using the brackets {} you can use phrases as the variable name.
${This is a test}=4
         Sets value of 4 to variable This is a test
${This is a test}
        Call variable This is a test
4
        Results

Read-Host
  Now it is all nice that we can static set a variable but what if I want to ask the user for information (name/amount/etc).  To do this we use:

Read-Host  "Message here"

To save this to a variable we just append $var = to the front of string as below:

$myvar = Read-Host "Enter Computer name:"
        Prompts the user to enter a value and saves it to variable myvar

Check out the rest of this segment:
Part 1: http://cleeit.blogspot.com/2014/01/MVA-powershell-m07-part1.html
Part 3: http://cleeit.blogspot.com/2014/01/MVA-powershell-m07-part3.html

Microsoft Virtual Academy: PowerShell M07 (Part 1)

Here we are module 7 only two more.  This is a short segment but lots of information.  To keep things short I have split it among three posts.  Check the Overview to see what is covered under this post.

To start your own learning check out Microsoft Virtual Academy:
(http://www.microsoftvirtualacademy.com/training-courses/getting-started-with-powershell-3-0-jump-start?o=3276#?fbid=aVs9FfAH2DJ)
(rewritten based on my notes available here: https://drive.google.com/file/d/0B1fwreWrAZioQ28xTmx0d29HUzQ/edit?usp=sharing)

Module 7: "Getting prepared for automation" consists of 2 video segments totaling ≈ 26 minutes along with a PowerPoint of 12 slides.

Overview
Execution Policy

   The execution policy is your safety net when it comes to PowerShell. The requirement for execution policy to allow a script to run is digitally signed and must be trusted.  This is different from VB scripts that just required them to be signed. With all the power that you have in scripts it is the execution policy that prevents malicious attacks.  By default it is set to restricted (on 2012R2 believe it is now RemoteSigned). To see what level your execution policy is at run following:

 Get-ExecutionPolicy 

   There are six levels of security: Restricted, Unrestricted, AllSigned, RemoteSigned, Bypass, and Undefined.  For more details on levels check out TechNet article: http://technet.microsoft.com/en-us/library/hh849812.aspx.  Note of warning avoid using Unrestricted and Bypass. For this module we focus in on RemoteSigned and AllSigned.  RemoteSigned is best for users starting out as it will allow an local created scripts to be ran without being signed, whereas AllSigned will require all scripts to be signed.

   Execution policy can be set through group policies (GPO) or at individual systems.  For GPO instructions check out this TechRepublic article: http://www.techrepublic.com/blog/the-enterprise-cloud/set-the-powershell-execution-policy-via-group-policy/ for individual systems you would execute following code:

 Set-ExecutionPolicy “[desired level]” 

Eample:
 Set-ExecutionPolicy “remotesigned” 

Signing Scripts

   As you work on creating scripts and securing your network you will at some point move to AllSigned.  This will require all scripts to be signed including the ones you create on a local system.  The following will walk you through how to sign a script.

Create
   To start you first need a self-signed certificate to use for signing.

New-SelfSignCertificate
    v3 or higher (Version 2 or non Win8/2k12 will use makecert.  More details here: http://www.hanselman.com/blog/SigningPowerShellScripts.aspx)

Load
    Now we need to find this self-signed certificate and load for future use.

Get-PSDrive
  Displays drives available during PowerShell session

Dir Cert:\CurrentUser -Recurse -CodeSigningCert -OutVariable a
  Pulls all certs created for current users with code signing rights and assigns them to variable a

$cert = $a[0]
  Takes and assigns first certificate from variable a to variable cert

Sign
   Now that we have a certificate loaded into $cert we can sign our scripts using the following code:

Set-AuthenticodeSignature -Certificate $cert -FilePath [pathtoscript]

Example:
Set-AuthenticodeSignature -Certificate $cert -FilePath C:\_scripts\hello.ps1

Results
   Now that we have a signed script set execution policy to all signed.  When you try to run you are prompted with choices:

  • Never Run
    • Does not run and adds certificate to blocked or untrusted list
  • Do not run
    • Does not run and does nothing with cert
  • Run Once
    • Runs but does nothing with cert
  • Always Run
    • Runs and adds certificate to trusted/allowed list
Check out the rest of this segment:
Part 2: http://cleeit.blogspot.com/2014/01/MVA-powershell-m07-part2.html
Part 3: http://cleeit.blogspot.com/2014/01/MVA-powershell-m07-part3.html

Monday, January 6, 2014

Microsoft Virtual Academy: PowerShell M06

Well it has been a hectic holiday period but back to work, I am behind on getting my notes converted into posts.  We should be finishing up this series by the end of Jan.

To start your own learning check out Microsoft Virtual Academy:
(http://www.microsoftvirtualacademy.com/training-courses/getting-started-with-powershell-3-0-jump-start?o=3276#?fbid=aVs9FfAH2DJ)
(rewritten based on my notes available here: https://drive.google.com/file/d/0B1fwreWrAZioQ28xTmx0d29HUzQ/edit?usp=sharing)

Module 6 "The PowerShell in the shell: remoting" consists of 3 video segments totaling ≈ 55 minutes along with a PowerPoint of 11 slides.

Overview:
  • Remoting
    • Security
    • Enabling Remoting
    • Remoting
      • One-to-One
      • One-to-Many
  • PowerShell via web
Security

    To start lets get the security stuff out of the way.  PowerShell uses Kerboros to encrypt all transmissions from the terminal to the remote system. It can be further secured with the use of SSL.  This allows for easier firewall management as it uses a single port.  

Enable Remoting

    Two ways to enable PowerShell remoting.  First is to log on to each server/system and execute:

Enabling Remoting

   This is time and energy consuming.  The second way is more efficient and that is with use of GPOs.  Check out the links below for more details:

How To Enable Powershell Remoting - Spiceworks - Martin9700
      http://community.spiceworks.com/how_to/show/18512-how-to-enable-powershell-remoting


Enable and configure Windows PowerShell Remoting using Group Policy - blog.powershell.no
     http://blog.powershell.no/2010/03/04/enable-and-configure-windows-powershell-remoting-using-group-policy/

Remoting

    Once you have enabled PowerShell Remoting there are two ways to manage systems: one-to-one and one-to-many. As you may guess that is control system to remote systems.  Depending on how many systems you are controlling will impact the way PowerShell interacts with them.  Remember when remoting the work is completed on remote system and not on local/management system.

One-to-One
   This process allows you to interact with the remote system similar to being directly logged on. To access remote system use:

Enter-PSSession -ComputerName [computername]

Example:
Enter-PSSession -ComputerName DC


Once you have access to the system you PowerShell prompt will change to resemble following: [computername]: PS C:\>.  You can now run cmdlets as you would on local system.  This is handy if you need full access to a system can't access directly.

One-to-Many
   This process accesses multiple systems and returns results as objects.  To execute use the following:
      
Invoke-Command -ComputerName [computernames seperated by comma] {cmdlet} 

Example:
Invoke-Command -ComputerName dc,dc1 {Get-EventLog -LogName System  -new 3}



PowerShell via web
   Want to or need the ability to access PowerShell via the web?  How about from mobile devices?  Well they thought of this and have provided a solution for version 3 and higher.

   To accomplish this we will install Windows PowerShell Web Access (pswa).  This consists of roughly three commands to complete.   It will install IIS and .Net 4.5 if not already installed.  To start we first run:

Install-WindowsFeature WindowsPowerShellWebAccess
         (Installs IIS and .Net 4.5)

Install-PSWAWebApplication
          (Sets up and cinfigures IIS for pswa)

Add-PSWAAuthrizationRule -ComputerName [name] -username [users] -configurations
          (More details available here:http://technet.microsoft.com/en-us/library/jj592890.aspx)

   Once completed you (and firewall configured correctly) you can browse to your new IIS site and access PowerShell through HTTPS.

Resources mentioned in module:
   Secrets of PowerShell: Remoting
       https://github.com/PowerShellOrg/ebooks/tree/master/Remoting

Monday, December 23, 2013

Microsoft Virtual Academy: PowerShell M05

Today I continue forward on my goal of completing Microsoft's Virtual Academy's PowerShell 3.0 training.
(http://www.microsoftvirtualacademy.com/training-courses/getting-started-with-powershell-3-0-jump-start?o=3276#?fbid=aVs9FfAH2DJ)
(rewritten based on my notes available here: https://drive.google.com/file/d/0B1fwreWrAZioUWpaeFNSTFVXUEU/edit?usp=sharing)

Module 5 "Te pipeline:deeper" consists of 3 video segments totaling ≈ 45 minutes along with a PowerPoint of 12 slides.

The focus of this segment is on the pipeline ( | )

As briefly mentioned in past segments the pipeline allows us to pass objects along a string of cmdlets. The pipeline has four (4) ways to be used:

  1. ByValue
  2. ByPropertyName
  3. Customized properties
  4. Parenthetical
First and most common use is through the ByValue. In order to use ByValue we need to know the following: type of object we sending and if the receiving cmdlet can accept it.  To determine the type of our object we use get-member (gm).  Know to validate the receiving cmdlet we run a get-help [cmdlet].  There are two (2) things we are looking for in the help file.  First, if any parameters accept pipeline input and second if any parameters accept our object type.  

Example: Get-Service | Stop-Service
  1. Determine object type: 
    • Get-Service | gm
    • Results: TypeName: System.ServiceProcess.ServiceController
  2. Verify receive cmdlet will accept
    • Get-Help stop-service -full
      • If using v3 use -showWindow and utilize the search feature
    • Verify accept pipeline input: true (.., ByValue,..)
    • Verify input value is sending object type
      • -InputObject <ServiceController[]>
Hint:  if the nouns match most likely will work.


Next we move to the ByPropertyName.  Works very similar to ByValue but is more forgiving.  We follow the same process of verify.  This process works on the concept of a property of sending object matching a parameter in receiving cmdlet.


Example: Get-Service | Stop-Process
  1. Determine object type: 
    • Get-Service | gm
    • Results: TypeName: System.ServiceProcess.ServiceController
  2. Verify receive cmdlet will accept
    • Get-Help stop-process -full
    • Verify accept pipeline input: true (.., ByValue,..)
    • Verify input value is sending object type
      • -InputObject <Process[]>
        • Not the same type so now we look for ByPropertyName
      • -Name <String[]>
        • Will accept input from sending object's property name and process based on that
So what if ByValue and ByPropertyName don't work?  We can create a custom property.  This is accomplished by creating a custom column (calculated property).  With a custom property are goal is to meet the ByPropertyName process.  In the example below and in segment we try to send ADComputer to Get-Service.

Command used:  @{name=’[propertyname]’;expression={$_.[property]}}

Example: Get-ADComputer -filter * | Get-Service -name bits

  1. Determine object type: 
    • Get-ADComputer | gm
    • Results: TypeName: Microsoft.ActiveDirectory.Management.ADComputer
  2. Verify receive cmdlet will accept
    • Get-Help Get-Service -full
      • ByValue: -InputObject <ServiceController[]> - No Go
      • ByPropertyName: -ComputerName (for systems), -Name (for services)
        • We want to use the -ComputerName and not -Name, this is where custom property comes in
  3. Map ADComputer -Name to -ComputerName
    • @{name=’ComputerName’;expression={$_.name}}
  4. Verify Object Property
    • Get-ADComputer | gm
      • Should now see a property called ComputerName

Finally we use Parenthetical when all else has failed us.  Command process what is in parenthesis first.

For this example we want to pull all BIOS details for all ADComputers.

Example: Get-ADComputer –filter * | get-WMIObject –class win32bios

  1. Determine object type: 
    • Get-ADComputer | gm
    • Results: TypeName: Microsoft.ActiveDirectory.Management.ADComputer
  2. Verify receive cmdlet will accept
    • Get-Help Get-WMIObject -full
      • Notice there is no pipeline support
As we see WMIObject does not support pipeline.  To work around this we use -ExpandProperty.  -ExpandProperty will expand a single property into a string object. There are two ways to accomplish this dependent on version you are running.

Command used: Get-adcomputer –filter * | select –ExpandProperty name

If we run this through gm we find object type is no a string.

  • v2 and v3
    • Get-wmiobject –class  win32_bios –ComputerName (Get-adcomputer –filter * | select –ExpandProperty name)
  • v3 only
    • Get-wmiobject –class  win32_bios –ComputerName (Get-adcomputer –filter *).name
That wraps up segment 5.  I hope to have segment 6 up next week but dependent on the holidays and work it may not be up until Mid-January. 

I hope everyone has Happy Holidays.