Public/ScreenPNG.ps1

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
<#
.SYNOPSIS
Captures a PowerShell Screenshot
 
.DESCRIPTION
Captures a PowerShell Screenshot and saves the image in the -Directory $Env:TEMP\Screenshot by default
 
.LINK
https://osd.osdeploy.com/module/functions/general/get-screenpng
 
.NOTES
21.1.23 Initial Release
 
#>

function Get-ScreenPNG {
    [CmdletBinding()]
    param (
        #Directory where the Screenshots will be saved
        #Default = $Env:TEMP\Screenshots
        [string]$Directory = $null,

        #Saved files will have a Screenshot prefix in the filename
        [string]$Prefix = $null,

        #Delay before taking a Screenshot in seconds
        #Default: 0 (1 Count)
        #Default: 1 (>1 Count)
        [uint32]$Delay = 0,

        #Total number of Screenshots to capture
        #Default = 1
        [uint32]$Count = 1,

        #Additionally copies the Screenshot to the Clipboard
        [switch]$Clipboard = $false,

        #Screenshot of the Primary Display only
        [switch]$Primary = $false
    )
    begin {
        #=================================================
        # Gather
        #=================================================
        $GetCommandNoun = Get-Command -Name Get-ScreenPNG | Select-Object -ExpandProperty Noun
        $GetCommandVersion = Get-Command -Name Get-ScreenPNG | Select-Object -ExpandProperty Version
        $GetCommandHelpUri = Get-Command -Name Get-ScreenPNG | Select-Object -ExpandProperty HelpUri
        $GetCommandModule = Get-Command -Name Get-ScreenPNG | Select-Object -ExpandProperty Module
        $GetModuleDescription = Get-Module -Name $GetCommandModule | Select-Object -ExpandProperty Description
        $GetModuleProjectUri = Get-Module -Name $GetCommandModule | Select-Object -ExpandProperty ProjectUri
        $GetModulePath = Get-Module -Name $GetCommandModule | Select-Object -ExpandProperty Path
        $MyPictures = (New-Object -ComObject Shell.Application).NameSpace('shell:My Pictures').Self.Path
        #=================================================
        # Adjust Delay
        #=================================================
        if ($Count -gt '1') {if ($Delay -eq 0) {$Delay = 1}}
        #=================================================
        # Determine Task Sequence
        #=================================================
        $LogPath = ''
        $SMSTSLogPath = ''
        try {
            $TSEnv = New-Object -ComObject Microsoft.SMS.TSEnvironment -ErrorAction SilentlyContinue
            $IsTaskSequence = $true
            $LogPath = $TSEnv.Value('LogPath')
            $SMSTSLogPath = $TSEnv.Value('_SMSTSLogPath')
        }
        catch [System.Exception] {
            $IsTaskSequence = $false
            $LogPath = ''
            $SMSTSLogPath = ''
        }
        #=================================================
        # Set AutoPath
        #=================================================
        if ($Directory -eq '') {
            if ($IsTaskSequence -and (Test-Path $LogPath)) {
                $AutoPath = Join-Path -Path $LogPath -ChildPath "Screenshots"
            } elseif ($IsTaskSequence -and (Test-Path $SMSTSLogPath)) {
                $AutoPath = Join-Path -Path $SMSTSLogPath -ChildPath "Screenshots"
            } elseif ($env:SystemDrive -eq 'X:') {
                $AutoPath = 'X:\Screenshots'
            } elseif (Test-Path $MyPictures) {
                $AutoPath = Join-Path -Path $MyPictures -ChildPath "Screenshots"
            } else {
                $AutoPath = "$Env:TEMP\Screenshots"
            }
        } else {
            $AutoPath = $Directory
        }
        #=================================================
        # Usage
        #=================================================
        Write-Verbose '======================================================================================================'
        Write-Verbose "$GetCommandNoun $GetCommandVersion $GetCommandHelpUri"
        Write-Verbose $GetModuleDescription
        Write-Verbose "Module Path: $GetModulePath"
        Write-Verbose '======================================================================================================'
        Write-Verbose 'Get-ScreenPNG [[-Directory] <String>] [[-Prefix] <String>] [[-Delay] <UInt32>] [[-Count] <UInt32>] [-Clipboard] [-Primary]'
        Write-Verbose ''
        Write-Verbose '-Directory Directory where the Screenshots will be saved'
        Write-Verbose ' If this value is not set, Path will be automatically set between the following:'
        Write-Verbose ' Defaults = [LogPath\Screenshots] [_SMSTSLogPath\Screenshots] [My Pictures\Screenshots] [$Env:TEMP\Screenshots]'
        Write-Verbose " Value = $AutoPath"
        Write-Verbose ''
        $DateString = (Get-Date).ToString('yyyyMMdd_HHmmss')
        Write-Verbose "-Prefix Pattern in the file name $($Prefix)_$($DateString).png"
        Write-Verbose " Default = Screenshot"
        Write-Verbose " Value = $Prefix"
        Write-Verbose ''
        Write-Verbose '-Count Total number of Screenshots to capture'
        Write-Verbose ' Default = 1'
        Write-Verbose " Value = $Count"
        Write-Verbose ''
        Write-Verbose '-Delay Delay before capturing the Screenshots in seconds'
        Write-Verbose ' Default = 0 (Count = 1) | Default = 1 (Count > 1)'
        Write-Verbose " Value = $Delay"
        Write-Verbose ''
        Write-Verbose '-Clipboard Additionally copies the Screenshot to the Clipboard'
        Write-Verbose " Value = $Clipboard"
        Write-Verbose ''
        Write-Verbose '-Primary Captures Screenshot from the Primary Display only for Multiple Displays'
        Write-Verbose " Value = $Primary"
        Write-Verbose '======================================================================================================'
        #=================================================
        # Load Assemblies
        #=================================================
        Add-Type -Assembly System.Drawing
        Add-Type -Assembly System.Windows.Forms
        #=================================================
    }
    process {
        foreach ($i in 1..$Count) {
            #=================================================
            # Determine Task Sequence (Process Block)
            #=================================================
            $LogPath = ''
            $SMSTSLogPath = ''
            try {
                $TSEnv = New-Object -ComObject Microsoft.SMS.TSEnvironment -ErrorAction SilentlyContinue
                $IsTaskSequence = $true
                $LogPath = $TSEnv.Value('LogPath')
                $SMSTSLogPath = $TSEnv.Value('_SMSTSLogPath')
            }
            catch [System.Exception] {
                $IsTaskSequence = $false
                $LogPath = ''
                $SMSTSLogPath = ''
            }
            #=================================================
            # Set AutoPath (Process Block)
            #=================================================
            $AutoPathBackup = $AutoPath
            if ($Directory -eq '') {
                if ($IsTaskSequence -and (Test-Path $LogPath)) {
                    $AutoPath = Join-Path -Path $LogPath -ChildPath "Screenshots"
                } elseif ($IsTaskSequence -and (Test-Path $SMSTSLogPath)) {
                    $AutoPath = Join-Path -Path $SMSTSLogPath -ChildPath "Screenshots"
                } elseif ($env:SystemDrive -eq 'X:') {
                    $AutoPath = 'X:\Screenshots'
                } elseif (Test-Path $MyPictures) {
                    $AutoPath = Join-Path -Path $MyPictures -ChildPath "Screenshots"
                } else {
                    $AutoPath = "$Env:TEMP\Screenshots"
                }
            } else {
                $AutoPath = $Directory
            }
            Write-Verbose "AutoPath is set to $AutoPath"
            #=================================================
            # AutoPathBackup
            #=================================================
            if ($AutoPathBackup -ne $AutoPath) {
                #Path changed, so need to move the content from the previous AutoPath
            }
            #=================================================
            # Determine AutoPath
            #=================================================
            if (!(Test-Path "$AutoPath")) {
                Write-Verbose "Creating snaScreenshot directory at $AutoPath"
                New-Item -Path "$AutoPath" -ItemType Directory -Force -ErrorAction Stop | Out-Null
            }
            #=================================================
            # Delay
            #=================================================
            Write-Verbose "Delay $Delay Seconds"
            Start-Sleep -Seconds $Delay
            #=================================================
            # Display Information
            #=================================================
            $GetDisplayAllScreens = @(Get-DisplayAllScreens)
            $GetDisplayVirtualScreen = Get-DisplayVirtualScreen
            #=================================================
            # Display Number
            #=================================================
            foreach ($Device in $GetDisplayAllScreens) {
                #DateString
                $DateString = (Get-Date).ToString('yyyyMMdd_HHmmss')
                
                #DisplayNumber
                $DisplayNumber = $Device.DeviceName -Replace "[^0-9]"
                Write-Verbose "DisplayNumber: $DisplayNumber"

                #FileName
                if ($Prefix) {
                    $FileName = "$($Prefix)_$($DateString)"
                } else {
                    $FileName = "$($DateString)"
                }

                if ($GetDisplayAllScreens.Count -eq 1) {
                    $FileName = "$($FileName).png"
                } else {
                    $FileName = "$($FileName)_$($DisplayNumber).png"
                }

                if ($Device.Primary -eq $true) {
                    $GetDisplayPrimaryBitmapSize = Get-DisplayPrimaryBitmapSize
                    #Write-Verbose "Width: $($GetDisplayPrimaryBitmapSize.Width)" -Verbose
                    #Write-Verbose "Height: $($GetDisplayPrimaryBitmapSize.Height)" -Verbose
                    $ScreenshotBitmap = New-Object System.Drawing.Bitmap $GetDisplayPrimaryBitmapSize.Width, $GetDisplayPrimaryBitmapSize.Height
                    $ScreenshotGraphics = [System.Drawing.Graphics]::FromImage($ScreenShotBitmap)
                    #Write-Verbose "X: $($GetDisplayVirtualScreen.X)" -Verbose
                    #Write-Verbose "Y: $($GetDisplayVirtualScreen.Y)" -Verbose
                    #Write-Verbose "Size: $($GetDisplayVirtualScreen.Size)" -Verbose
                    $ScreenshotGraphics.CopyFromScreen($GetDisplayVirtualScreen.X, $GetDisplayVirtualScreen.Y, $GetDisplayVirtualScreen.X, $GetDisplayVirtualScreen.Y, $GetDisplayVirtualScreen.Size)
                    Write-Verbose "Saving Primary Screenshot $i of $Count to to $AutoPath\$FileName"
                }
                
                if ($Device.Primary -eq $false) {
                    if ($Primary -eq $true) {Continue}
                    Write-Verbose "Width: $($Device.Bounds.Width)" -Verbose
                    Write-Verbose "Height: $($Device.Bounds.Height)" -Verbose
                    $ScreenshotBitmap = New-Object System.Drawing.Bitmap $Device.Bounds.Width, $Device.Bounds.Height
                    $ScreenshotGraphics = [System.Drawing.Graphics]::FromImage($ScreenShotBitmap)
                    Write-Verbose "X: $($Device.Bounds.X)" -Verbose
                    Write-Verbose "Y: $($Device.Bounds.Y)" -Verbose
                    Write-Verbose "Size: $($GetDisplayVirtualScreen.Size)" -Verbose
                    $ScreenshotGraphics.CopyFromScreen($Device.Bounds.X, $Device.Bounds.Y, 0, 0, $GetDisplayVirtualScreen.Size)
                    Write-Verbose "Saving Secondary Screenshot $i of $Count to to $AutoPath\$FileName"
                }

                #=================================================
                # Save the Screenshot to File
                # https://docs.microsoft.com/en-us/dotnet/api/system.drawing.image.tag?view=dotnet-plat-ext-5.0
                #=================================================
                $ScreenshotBitmap.Save("$AutoPath\$FileName")

                #=================================================
                # Copy the Screenshot to the Clipboard
                # https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.clipboard.setimage?view=net-5.0
                #=================================================
                if ($Device.Primary -eq $true) {
                    if ($Clipboard) {
                        Write-Verbose "Copying Screenshot to the Clipboard"
                        #Add-Type -Assembly System.Drawing
                        #Add-Type -Assembly System.Windows.Forms
                        [System.Windows.Forms.Clipboard]::SetImage($ScreenshotBitmap)
                    }
                }
            }
            #=================================================
            # Close
            #=================================================
            $ScreenshotGraphics.Dispose()
            $ScreenshotBitmap.Dispose()
            #=================================================
            # Return Get-Item
            #=================================================
            Get-Item "$AutoPath\$FileName"
            #=================================================
        }
    }
    end {}
}
function Start-ScreenPNGProcess {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$Directory,

        [uint32]$Delay = 2,

        [uint32]$Count = 9999
    )

    $StartInfo = new-object System.Diagnostics.ProcessStartInfo
    $StartInfo.FileName = 'powershell.exe'
    $StartInfo.Arguments = "-NoExit -WindowStyle Hidden -Command Get-ScreenPNG -Directory $Directory -Count $Count -Delay $Delay"
    $Global:ScreenPNGPath = $Directory
    $Global:ScreenPNGProcess = ([System.Diagnostics.Process]::Start($StartInfo)).Id
}
function Stop-ScreenPNGProcess {
    [CmdletBinding()]
    param ()

    Stop-Process -Id $Global:ScreenPNGProcess -Force -ErrorAction SilentlyContinue
    $Global:ScreenPNGPath = $null
    $Global:ScreenPNGProcess = $null
}