Форум программистов, компьютерный форум, киберфорум
PowerShell
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.77/13: Рейтинг темы: голосов - 13, средняя оценка - 4.77
1 / 1 / 0
Регистрация: 30.09.2014
Сообщений: 53

Формат Send-MailMessage

17.07.2019, 11:20. Показов 2796. Ответов 4
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Добрый день.

Я написал скрипт который посылает эл.письмо, но в письме строки не отсортированы, пробовал использовать FT -AutoSize и конвертировать в html, результат в Powershell ISE отличный, все столбцы друг под другом, а в письме нет.

Посоветуйте как можно это поправить.

PowerShell
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
# Specify target folder or network share.
$share="\\SERVERNAME\FOLDER\PACKAGE"
$TargetFolder= Read-Host -Prompt 'Insert path name'
$reportfoldername= Get-ItemProperty -Path $TargetFolder | Select-Object -ExpandProperty name
# User friendly expressions used in result section.
$FileSize= @{Name="File size (MB)" ; Expression ={$_.Length/1MB -as [int]}}
$LastModified=@{Name="Date Modified"; Expression={$_.LastWriteTime.ToString("dd.MM.yyyy")}}
$result= Get-ChildItem $TargetFolder -Recurse | Where-Object { !$_.PSIsContainer} | Sort-Object -Property @{Expression={$_.LastWriteTime}} | Select-Object Name, $FileSize 
 
# Report part
$reportfoldername
$result
$MB= $result | Measure-Object -Property "File size (MB)" -Sum | Select-Object -ExpandProperty sum
Write-Output ""Total:"$MB "MB""  | Format-Table -Property Name 
$result + "`r`nTotal: $MB MB" | Out-File $share\result.log
 
# Saving upload data to share.
if (!(Test-Path "$share\uploaded.txt"))
{
   New-Item -path $share -name uploaded.txt -type "file"
}
 
$uploaded = get-content $share\uploaded.txt
#$uploaded = $MB | Out-file $share\uploaded.txt
$upload = $MB
$Total = [int]$uploaded + [int]$upload
$Total | Out-File -FilePath $share\uploaded.txt -force
 
$smtpserver="smtp.server"
$smtpfrom="email.address@domain.com"
$smtpto="username@domain.com"
$messagesubject="Upload report"
$uploaded = get-content $share\uploaded.txt
Write-Output "Today's upload summary: $uploaded MB" | out-file -FilePath "$share\result.log" -Append
$filecontent= Get-Content "$share\result.log"
 
[string]$messagebody=''
 
$OFS*=*"`r`n"
foreach ($line in $filecontent)
{
    #[string]$Global:messagebody = $messagebody + $line + $ofs
    $messagebody = $messagebody + $line + $ofs
}  
 
Send-MailMessage -from $smtpfrom -to $smtpto -Subject $messagesubject -Body $messagebody -SmtpServer $smtpserver
Результат не могу запостить, но столбцы в письме съехавшие в сторону и размер файлов не находиться друг под другом.
0
Лучшие ответы (1)
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
17.07.2019, 11:20
Ответы с готовыми решениями:

Сообщение об ошибке "Send-MailMessage : Время ожидания операции истекло." при отправке письма
Привет! Пытаюсь отправить письмо следующей командой: $pwd = ConvertTo-SecureString "testPassword" -AsPlainText -Force;...

Сообщение MailMessage
Всем привет! Нашёл инете код для формирования email'а. Всё понятно кроме 2-х строк: mail.DeliveryNotificationOptions =...

Exception с SmtpClient и MailMessage
Пробовал отправить сообщение через smtp, но вылетает ексепшин вот код: public void email_send() { ...

4
 Аватар для KDE777
1886 / 1108 / 428
Регистрация: 22.01.2016
Сообщений: 3,050
19.07.2019, 11:41
Лучший ответ Сообщение было отмечено vorkpallur как решение

Решение

Цитата Сообщение от vorkpallur Посмотреть сообщение
пробовал использовать FT -AutoSize и конвертировать в html
Использование Format-Table, для чего-то кроме вывода на экран консоли, очень плохая идея.

PowerShell
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
# Specify target folder or network share.
$share            = "\\SERVERNAME\FOLDER\PACKAGE"
$TargetFolder     = Read-Host -Prompt 'Insert path name'
$ReportFolderName = Get-ItemProperty -Path $TargetFolder -ErrorAction Stop | Select-Object -ExpandProperty name
 
# User friendly expressions used in result section.
$result = Get-ChildItem -Path $TargetFolder -Recurse -File | Sort-Object -Property LastWriteTime | Select-Object -Property `
    Name,
    @{N = "File size (MB)"; E = {[math]::Round($_.Length/1MB,0)}},
    @{N = "Date Modified";  E = {$_.LastWriteTime.ToString("dd.MM.yyyy")}}
 
$MB = $result | Measure-Object -Property "File size (MB)" -Sum | Select-Object -ExpandProperty sum
 
# Saving upload data to share.
if (Test-Path "$share\uploaded.txt")
{
    [int]$uploaded = Get-Content $share\uploaded.txt
}
else
{
    New-Item -Path $share -Name uploaded.txt -Type "file"
    [int]$uploaded = 0
} 
 
Set-Content -Value ($uploaded + $MB) -LiteralPath $share\uploaded.txt -Encoding UTF8
 
$txtReport  = $ReportFolderName
$txtReport += $result | Out-String
$txtReport += "Total: $MB MB`r`nToday's upload summary: $uploaded MB" 
 
cls; $txtReport | Tee-Object -LiteralPath $share\result.log
 
$smtpserver     = "smtp.server"
$smtpfrom       = "email.address@domain.com"
$smtpto         = "username@domain.com"
$messagesubject = "Upload report"
 
$htmlReport = "<html><body><p><BR>Отчёт о файлах в папке: $ReportFolderName<BR><BR>"
$htmlReport += $result | ConvertTo-Html
$htmlReport += "<BR><BR>Total: $MB MB<BR><BR>Today's upload summary: $uploaded MB</p></body></html>"
 
$htmlBody = $htmlReport | Out-String
Send-MailMessage -From $smtpfrom -To $smtpto -Subject $messagesubject -SmtpServer $smtpserver -Body $htmlBody -BodyAsHtml -Encoding ([System.Text.Encoding]::UTF8)
1
 Аватар для v_svitere
774 / 423 / 137
Регистрация: 03.06.2009
Сообщений: 1,223
Записей в блоге: 4
19.07.2019, 17:09
Кстати у командлета ConvertTo-Html есть очень полезный функционал -Fragment.

Можно сформировать табличный объект, например ArrayList, сконверитировать ее в HTML-формат и вставить в общий Body
0
1 / 1 / 0
Регистрация: 30.09.2014
Сообщений: 53
31.07.2019, 14:31  [ТС]
Спасибо KDE777, Ваше решение было именно тем, что мне нужно было!
Теперь буду думать как сделать возможным вносить несколько шар, т.е. столько сколько нужно пользователю.
А вообще я почитал и мне понравилась идея drag-drop контента, что было бы намного удобнее и проще в использовании, но в рамках данного поста я благодарю за помощь!

С уважением,
Пётр

Добавлено через 3 минуты
Спасибо KDE777.
Я почитал, что можно реализовать drag-drop для аналогичной задачи считывать размер папок, но это потом буду думать как реализовать, а на данный момент спасибо за помощь!

Пётр

Добавлено через 1 час 7 минут
Нашел на windows 10 форуме как реализовать DRAG&DROP.
Интересно, найдется ли здесь специалиста который сможет помочь вмонтировать мое решение в DRAG&DROP таким образом, чтобы кидать папку и получать по почте репорт по размеру файлов в папке с названием папки?

Сам скрипт здесь, но если это сверх просьба, то я не настаиваю! К сожалению в данный момент это сверх моих сил реализовать.

PowerShell
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
<#
__          ___           _                  __  ___  ______                                            
\ \        / (_)         | |                /_ |/ _ \|  ____|                                            
\ \  /\  / / _ _ __   __| | _____      _____| | | | | |__ ___  _ __ _   _ _ __ ___  ___   ___ ___  _ __ ___
  \ \/  \/ / | | '_ \ / _` |/ _ \ \ /\ / / __| | | | |  __/ _ \| '__| | | | '_ ` _ \/ __| / __/ _ \| '_ ` _ \
   \  /\  /  | | | | | (_| | (_) \ V  V /\__ \ | |_| | | | (_) | |  | |_| | | | | | \__ \| (_| (_) | | | | | |
    \/  \/   |_|_| |_|\__,_|\___/ \_/\_/ |___/_|\___/|_|  \___/|_|   \__,_|_| |_| |_|___(_)___\___/|_| |_| |_|
 
 
PowerShell Script Repository: https://www.windows10forums.com/articles/categories/powershell-scripts.8/
Author: Regedit32
#>
 
Add-Type -AssemblyName System.Windows.Forms
 
# All file types explored
Function AllFileExplorer {
 
  # Variable to store what user types into Input textbox
  $Input = $inputBox.Text
 
  # Set path to user's input
  Set-Location $Input
 
  # Create Temporary File
  foreach ($item in $outputBox) {
    # Set filepaths
    $str = Get-ChildItem -Filter *.*
  }
  $outputBox.Text = $str.FullName
  # Save Temporary file to Desktop
  $outputBox.Text.Split() | Out-File $env:USERPROFILE\Desktop\FilePath.txt -Append
  $outputBox.Clear()
 
  # Variable to store results of actioning the Input
  $Result = Get-ChildItem -Name $Input -Filter *.* | Out-String
 
 
  # Assign Result to OutputBox
  $outputBox.Text = $Result
}
 
# All Executable files in selected path explored
Function ExeFileExplorer {
 
  # Variable to store what user types into Input textbox
  $Input = $inputBox.Text
 
  # Set path to user's input
  Set-Location $Input
 
  # Create Temporary File
  foreach ($item in $outputBox) {
    # Set filepaths
    $str = Get-ChildItem -Filter *.exe
  }
  $outputBox.Text = $str.FullName
  # Save Temporary file to Desktop
  $outputBox.Text.Split() | Out-File $env:USERPROFILE\Desktop\FilePath.txt -Append
  $outputBox.Clear()
 
  # Variable to store results of actioning the Input
  $Result = Get-ChildItem -Name $Input -Filter *.exe | Out-String
 
  # Assign Result to OutputBox
  $outputBox.Text = $Result
}
 
# All DLL files in seleced path explored
Function DllFileExplorer {
 
  # Variable to store what user types into Input textbox
  $Input = $inputBox.Text
 
  # Set path to user's input
  Set-Location $Input
 
  # Create Temporary File
  foreach ($item in $outputBox) {
    # Set filepaths
    $str = Get-ChildItem -Filter *.dll
  }
  $outputBox.Text = $str.FullName
  # Save Temporary file to Desktop
  $outputBox.Text.Split() | Out-File $env:USERPROFILE\Desktop\FilePath.txt -Append
  $outputBox.Clear()
 
  # Variable to store results of actioning the Input
  $Result = Get-ChildItem -Name $Input -Filter *.dll | Out-String
 
  # Assign Result to OutputBox
  $outputBox.Text = $Result
}
 
 
# All SYS files of selected path explorered
Function SysFileExplorer {
 
  # Variable to store what user types into Input textbox
  $Input = $inputBox.Text
 
  # Set path to user's input
  Set-Location $Input
 
  # Create Temporary File
  foreach ($item in $outputBox) {
    # Set filepaths
    $str = Get-ChildItem -Filter *.sys
  }
  $outputBox.Text = $str.FullName
  # Save Temporary file to Desktop
  $outputBox.Text.Split() | Out-File $env:USERPROFILE\Desktop\FilePath.txt -Append
  $outputBox.Clear()
 
  # Variable to store results of actioning the Input
  $Result = Get-ChildItem -Name $Input -Filter *.sys | Out-String
  $str = Get-ChildItem -Filter *.sys
 
  # Assign Result to OutputBox
  $outputBox.Text = $Result
 
  Return $str
}
 
# All TXT files of selected path explored
Function TxtFileExplorer {
 
  # Variable to store what user types into Input textbox
  $Input = $inputBox.Text
 
  # Set path to user's input
  Set-Location $Input
 
  # Create Temporary File
  foreach ($item in $outputBox) {
    # Set filepaths
    $str = Get-ChildItem -Filter *.txt
  }
  $outputBox.Text = $str.FullName
  # Save Temporary file to Desktop
  $outputBox.Text.Split() | Out-File $env:USERPROFILE\Desktop\FilePath.txt -Append
  $outputBox.Clear()
 
  # Variable to store results of actioning the Input
  $Result = Get-ChildItem -Name $Input -Filter *.txt | Out-String
 
  # Assign Result to OutputBox
  $outputBox.Text = $Result
}
 
$Form = New-Object system.Windows.Forms.Form
$Form.Text = "Drag & Drop Files to listBox"
$Form.TopMost = $true
$Form.Width = 800
$Form.Height = 600
 
$listBox = New-Object system.windows.Forms.ListBox
$listBox.BackColor = "#9a94be"
$listBox.ForeColor = "#000000"
$listBox.Size = New-Object System.Drawing.Size(360,404)
$listBox.location = new-object system.drawing.point(400,137)
$listBox.Font = "Microsoft Sans Serif,10"
$listBox.AllowDrop = $true
 
$label2 = New-Object system.windows.Forms.Label
$label2.Text = "Drag `&& Drop Files or Directories Here"
$label2.AutoSize = $true
$label2.Width = 360
$label2.Height = 20
$label2.location = new-object system.drawing.point(400,100)
$label2.Font = "Microsoft Sans Serif,14"
 
$checkBox = New-Object system.windows.Forms.CheckBox
$checkBox.Text = "Clear "
$checkBox.AutoSize = $true
$checkBox.Width = 95
$checkBox.Height = 30
$checkBox.location = new-object system.drawing.point(710,60)
$checkBox.Font = "Microsoft Sans Serif,12,style=Bold"
 
# Create an Output textbox, 10 pixels in from Form Boundary and 150 pixels down
# As we want a multiline output set textbox size to 360 px x 400 px
# .Multiline declares the textbox is multi-line
# Declare vertical scrollbars
$outputBox = New-Object System.Windows.Forms.TextBox
$outputBox.Location = New-Object System.Drawing.Size(20,140)
$outputBox.Size = New-Object System.Drawing.Size(360,400)
$outputBox.MultiLine = $true
$outputBox.ScrollBars = "Vertical"
$outputBox.Font = "Microsoft Sans Serif,10"
 
# Buttons
$button1 = New-Object system.windows.Forms.Button
$button1.BackColor = "#000000"
$button1.Text = "*.*"
$button1.ForeColor = "#ffffff"
$button1.Width = 60
$button1.Height = 30
$button1.location = new-object system.drawing.point(20,100)
$button1.Font = "Microsoft Sans Serif,12"
 
$button2 = New-Object system.windows.Forms.Button
$button2.BackColor = "#000000"
$button2.Text = "EXE"
$button2.ForeColor = "#ffffff"
$button2.Width = 60
$button2.Height = 30
$button2.location = new-object system.drawing.point(90,100)
$button2.Font = "Microsoft Sans Serif,12"
 
$button3 = New-Object system.windows.Forms.Button
$button3.BackColor = "#000000"
$button3.Text = "DLL"
$button3.ForeColor = "#ffffff"
$button3.Width = 60
$button3.Height = 30
$button3.location = new-object system.drawing.point(160,100)
$button3.Font = "Microsoft Sans Serif,12"
 
$button4 = New-Object system.windows.Forms.Button
$button4.BackColor = "#000000"
$button4.Text = "SYS"
$button4.ForeColor = "#ffffff"
$button4.Width = 60
$button4.Height = 30
$button4.location = new-object system.drawing.point(230,100)
$button4.Font = "Microsoft Sans Serif,12"
 
$button5 = New-Object system.windows.Forms.Button
$button5.BackColor = "#000000"
$button5.Text = "TXT"
$button5.ForeColor = "#ffffff"
$button5.Width = 60
$button5.Height = 30
$button5.location = new-object system.drawing.point(300,100)
$button5.Font = "Microsoft Sans Serif,12"
 
$button6 = New-Object system.windows.Forms.Button
$button6.BackColor = "#4d194b"
$button6.Text = "Click to save as listBox.txt to Desktop"
$button6.ForeColor = "#ffffff"
$button6.Width = 300
$button6.Height = 30
$button6.location = new-object system.drawing.point(400,60)
$button6.Font = "Microsoft Sans Serif,12"
 
# Declare the action to occur when buttons clicked
$button1.Add_Click({ AllFileExplorer })
$button2.Add_Click({ ExeFileExplorer })
$button3.Add_Click({ DllFileExplorer })
$button4.Add_Click({ SysFileExplorer })
$button5.Add_Click({ TxtFileExplorer })
$button6.Add_Click($button6_Click)
 
# Input Box
$inputBox = New-Object system.windows.Forms.TextBox
$inputBox.Width = 360
$inputBox.Height = 20
$inputBox.location = new-object system.drawing.point(20,40)
$inputBox.Font = "Microsoft Sans Serif,10"
 
# Labels
$label1 = New-Object system.windows.Forms.Label
$label1.Text = "  Type Directory View (e.g. C:\Windows)  "
$label1.BackColor = "#b41c1f"
$label1.AutoSize = $true
$label1.ForeColor = "#ffffff"
$label1.Width = 360
$label1.Height = 30
$label1.location = new-object system.drawing.point(20,10)
$label1.Font = "Microsoft Sans Serif,14"
 
$label3 = New-Object system.windows.Forms.Label
$label3.Text = "Select File Extension to view"
$label3.AutoSize = $true
$label3.Width = 360
$label3.Height = 30
$label3.location = new-object system.drawing.point(20,70)
$label3.Font = "Microsoft Sans Serif,14"
 
# Add controls to form
$Form.SuspendLayout()
$Form.Controls.Add($button1)
$Form.Controls.Add($button2)
$Form.Controls.Add($button3)
$Form.Controls.Add($button4)
$Form.Controls.Add($button5)
$Form.Controls.Add($button6)
$Form.Controls.Add($checkBox)
$Form.Controls.Add($label1)
$Form.Controls.Add($label2)
$Form.Controls.Add($label3)
$Form.Controls.Add($inputBox)
$Form.Controls.Add($outputBox)
$Form.Controls.Add($listBox)
$Form.ResumeLayout()
# Event handlers
$button6_Click = {
  foreach ($item in $listBox) {
    # Save listBox to Desktop
    $listBox.Items | Out-File $env:USERPROFILE\Desktop\ListBox.txt -Append
  }
  if ($checkBox = 'Checked') {
    $listBox.Items.Clear()
  }
}
 
<#
   ------------------------------------------------------------
   OutputBox Event Handler
   Allows 1 or more items to be selected and dragged to listBox
   ------------------------------------------------------------ #>
$outputBox_MouseDown = [System.Windows.Forms.MouseEventHandler] {
  $outputBox.DoDragDrop($outputBox.Text,[System.Windows.Forms.DragDropEffects]::Copy)
}
 
<#
   ----------------------------------------------------------------------------------
   ListBox Event Handlers
   Sets the only location a dragged item can enter.  In this case that is the ListBox
   ----------------------------------------------------------------------------------  #>
$listBox_DragEnter = [System.Windows.Forms.DragEventHandler] {
  $_.Effect = $_.AllowedEffect
}
 
<#
   ------------------------------------------------------------------------
   > Set how to drop selected item(s) into ListBox
   > Makes use of [System.IO.File] to read each line
     of a file, then add each line to the ListBox.
 
     Required to prevent multiple items from a multiline TextBox
     appearing as one long line inside ListBox, rather than a list of items
     ---------------------------------------------------------------------- #>
$listBox_DragDrop = [System.Windows.Forms.DragEventHandler] {
 
  # Read Temorary File back into ListBox
  [string[]] $lines =  [System.IO.File]::ReadAllLines("$env:USERPROFILE\Desktop\FilePath.txt")
  [string] $line
 
  foreach ($line in $lines) {
    $listBox.Text = $listBox.Items.Add($line)
  }
  # Clear OutputBox
  $outputBox.Clear()
 
  # Delete Temporary File
  Remove-Item "$env:USERPROFILE\Desktop\FilePath.txt"
}
 
$form_FormClosed = {
  try {
    $Form.remove_FormClosed($Form_Cleanup_FormClosed)
    $outputBox.remove_MouseDown($outputBox_MouseDown)
    $listBox.remove_DragEnter($listBox_DragEnter)
    $listBox.remove_DragDrop($listBox_DragDrop)
  }
  catch [Exception] {}
}
#Initialize Events
$Form.Add_Click($button6_Click)
$button1.Add_Click($button1_Click)
$button2.Add_Click($button2_Click)
$button3.Add_Click($button3_Click)
$button4.Add_Click($button4_Click)
$button5.Add_Click($button5_Click)
$button6.Add_Click($button6_Click)
$outputBox.Add_MouseDown($outputBox_MouseDown)
$listBox.Add_DragEnter($listBox_DragEnter)
$listBox.Add_DragDrop($listBox_DragDrop)
 
$Form.Add_FormClosed($Form_FormClosed)
 
# Initialize Form
[void]$Form.ShowDialog()
$Form.Dispose()
0
1 / 1 / 0
Регистрация: 30.09.2014
Сообщений: 53
31.07.2019, 14:32  [ТС]
Нашел на windows 10 форуме как реализовать DRAG&DROP.
Интересно, найдется ли здесь специалиста который сможет помочь вмонтировать мое решение в DRAG&DROP таким образом, чтобы кидать папку и получать по почте репорт по размеру файлов в папке с названием папки?

Сам скрипт здесь, но если это сверх просьба, то я не настаиваю! К сожалению в данный момент это сверх моих сил реализовать.

PowerShell
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
<#
__          ___           _                  __  ___  ______                                            
\ \        / (_)         | |                /_ |/ _ \|  ____|                                            
\ \  /\  / / _ _ __   __| | _____      _____| | | | | |__ ___  _ __ _   _ _ __ ___  ___   ___ ___  _ __ ___
  \ \/  \/ / | | '_ \ / _` |/ _ \ \ /\ / / __| | | | |  __/ _ \| '__| | | | '_ ` _ \/ __| / __/ _ \| '_ ` _ \
   \  /\  /  | | | | | (_| | (_) \ V  V /\__ \ | |_| | | | (_) | |  | |_| | | | | | \__ \| (_| (_) | | | | | |
    \/  \/   |_|_| |_|\__,_|\___/ \_/\_/ |___/_|\___/|_|  \___/|_|   \__,_|_| |_| |_|___(_)___\___/|_| |_| |_|
 
 
PowerShell Script Repository: https://www.windows10forums.com/articles/categories/powershell-scripts.8/
Author: Regedit32
#>
 
Add-Type -AssemblyName System.Windows.Forms
 
# All file types explored
Function AllFileExplorer {
 
  # Variable to store what user types into Input textbox
  $Input = $inputBox.Text
 
  # Set path to user's input
  Set-Location $Input
 
  # Create Temporary File
  foreach ($item in $outputBox) {
    # Set filepaths
    $str = Get-ChildItem -Filter *.*
  }
  $outputBox.Text = $str.FullName
  # Save Temporary file to Desktop
  $outputBox.Text.Split() | Out-File $env:USERPROFILE\Desktop\FilePath.txt -Append
  $outputBox.Clear()
 
  # Variable to store results of actioning the Input
  $Result = Get-ChildItem -Name $Input -Filter *.* | Out-String
 
 
  # Assign Result to OutputBox
  $outputBox.Text = $Result
}
 
# All Executable files in selected path explored
Function ExeFileExplorer {
 
  # Variable to store what user types into Input textbox
  $Input = $inputBox.Text
 
  # Set path to user's input
  Set-Location $Input
 
  # Create Temporary File
  foreach ($item in $outputBox) {
    # Set filepaths
    $str = Get-ChildItem -Filter *.exe
  }
  $outputBox.Text = $str.FullName
  # Save Temporary file to Desktop
  $outputBox.Text.Split() | Out-File $env:USERPROFILE\Desktop\FilePath.txt -Append
  $outputBox.Clear()
 
  # Variable to store results of actioning the Input
  $Result = Get-ChildItem -Name $Input -Filter *.exe | Out-String
 
  # Assign Result to OutputBox
  $outputBox.Text = $Result
}
 
# All DLL files in seleced path explored
Function DllFileExplorer {
 
  # Variable to store what user types into Input textbox
  $Input = $inputBox.Text
 
  # Set path to user's input
  Set-Location $Input
 
  # Create Temporary File
  foreach ($item in $outputBox) {
    # Set filepaths
    $str = Get-ChildItem -Filter *.dll
  }
  $outputBox.Text = $str.FullName
  # Save Temporary file to Desktop
  $outputBox.Text.Split() | Out-File $env:USERPROFILE\Desktop\FilePath.txt -Append
  $outputBox.Clear()
 
  # Variable to store results of actioning the Input
  $Result = Get-ChildItem -Name $Input -Filter *.dll | Out-String
 
  # Assign Result to OutputBox
  $outputBox.Text = $Result
}
 
 
# All SYS files of selected path explorered
Function SysFileExplorer {
 
  # Variable to store what user types into Input textbox
  $Input = $inputBox.Text
 
  # Set path to user's input
  Set-Location $Input
 
  # Create Temporary File
  foreach ($item in $outputBox) {
    # Set filepaths
    $str = Get-ChildItem -Filter *.sys
  }
  $outputBox.Text = $str.FullName
  # Save Temporary file to Desktop
  $outputBox.Text.Split() | Out-File $env:USERPROFILE\Desktop\FilePath.txt -Append
  $outputBox.Clear()
 
  # Variable to store results of actioning the Input
  $Result = Get-ChildItem -Name $Input -Filter *.sys | Out-String
  $str = Get-ChildItem -Filter *.sys
 
  # Assign Result to OutputBox
  $outputBox.Text = $Result
 
  Return $str
}
 
# All TXT files of selected path explored
Function TxtFileExplorer {
 
  # Variable to store what user types into Input textbox
  $Input = $inputBox.Text
 
  # Set path to user's input
  Set-Location $Input
 
  # Create Temporary File
  foreach ($item in $outputBox) {
    # Set filepaths
    $str = Get-ChildItem -Filter *.txt
  }
  $outputBox.Text = $str.FullName
  # Save Temporary file to Desktop
  $outputBox.Text.Split() | Out-File $env:USERPROFILE\Desktop\FilePath.txt -Append
  $outputBox.Clear()
 
  # Variable to store results of actioning the Input
  $Result = Get-ChildItem -Name $Input -Filter *.txt | Out-String
 
  # Assign Result to OutputBox
  $outputBox.Text = $Result
}
 
$Form = New-Object system.Windows.Forms.Form
$Form.Text = "Drag & Drop Files to listBox"
$Form.TopMost = $true
$Form.Width = 800
$Form.Height = 600
 
$listBox = New-Object system.windows.Forms.ListBox
$listBox.BackColor = "#9a94be"
$listBox.ForeColor = "#000000"
$listBox.Size = New-Object System.Drawing.Size(360,404)
$listBox.location = new-object system.drawing.point(400,137)
$listBox.Font = "Microsoft Sans Serif,10"
$listBox.AllowDrop = $true
 
$label2 = New-Object system.windows.Forms.Label
$label2.Text = "Drag `&& Drop Files or Directories Here"
$label2.AutoSize = $true
$label2.Width = 360
$label2.Height = 20
$label2.location = new-object system.drawing.point(400,100)
$label2.Font = "Microsoft Sans Serif,14"
 
$checkBox = New-Object system.windows.Forms.CheckBox
$checkBox.Text = "Clear "
$checkBox.AutoSize = $true
$checkBox.Width = 95
$checkBox.Height = 30
$checkBox.location = new-object system.drawing.point(710,60)
$checkBox.Font = "Microsoft Sans Serif,12,style=Bold"
 
# Create an Output textbox, 10 pixels in from Form Boundary and 150 pixels down
# As we want a multiline output set textbox size to 360 px x 400 px
# .Multiline declares the textbox is multi-line
# Declare vertical scrollbars
$outputBox = New-Object System.Windows.Forms.TextBox
$outputBox.Location = New-Object System.Drawing.Size(20,140)
$outputBox.Size = New-Object System.Drawing.Size(360,400)
$outputBox.MultiLine = $true
$outputBox.ScrollBars = "Vertical"
$outputBox.Font = "Microsoft Sans Serif,10"
 
# Buttons
$button1 = New-Object system.windows.Forms.Button
$button1.BackColor = "#000000"
$button1.Text = "*.*"
$button1.ForeColor = "#ffffff"
$button1.Width = 60
$button1.Height = 30
$button1.location = new-object system.drawing.point(20,100)
$button1.Font = "Microsoft Sans Serif,12"
 
$button2 = New-Object system.windows.Forms.Button
$button2.BackColor = "#000000"
$button2.Text = "EXE"
$button2.ForeColor = "#ffffff"
$button2.Width = 60
$button2.Height = 30
$button2.location = new-object system.drawing.point(90,100)
$button2.Font = "Microsoft Sans Serif,12"
 
$button3 = New-Object system.windows.Forms.Button
$button3.BackColor = "#000000"
$button3.Text = "DLL"
$button3.ForeColor = "#ffffff"
$button3.Width = 60
$button3.Height = 30
$button3.location = new-object system.drawing.point(160,100)
$button3.Font = "Microsoft Sans Serif,12"
 
$button4 = New-Object system.windows.Forms.Button
$button4.BackColor = "#000000"
$button4.Text = "SYS"
$button4.ForeColor = "#ffffff"
$button4.Width = 60
$button4.Height = 30
$button4.location = new-object system.drawing.point(230,100)
$button4.Font = "Microsoft Sans Serif,12"
 
$button5 = New-Object system.windows.Forms.Button
$button5.BackColor = "#000000"
$button5.Text = "TXT"
$button5.ForeColor = "#ffffff"
$button5.Width = 60
$button5.Height = 30
$button5.location = new-object system.drawing.point(300,100)
$button5.Font = "Microsoft Sans Serif,12"
 
$button6 = New-Object system.windows.Forms.Button
$button6.BackColor = "#4d194b"
$button6.Text = "Click to save as listBox.txt to Desktop"
$button6.ForeColor = "#ffffff"
$button6.Width = 300
$button6.Height = 30
$button6.location = new-object system.drawing.point(400,60)
$button6.Font = "Microsoft Sans Serif,12"
 
# Declare the action to occur when buttons clicked
$button1.Add_Click({ AllFileExplorer })
$button2.Add_Click({ ExeFileExplorer })
$button3.Add_Click({ DllFileExplorer })
$button4.Add_Click({ SysFileExplorer })
$button5.Add_Click({ TxtFileExplorer })
$button6.Add_Click($button6_Click)
 
# Input Box
$inputBox = New-Object system.windows.Forms.TextBox
$inputBox.Width = 360
$inputBox.Height = 20
$inputBox.location = new-object system.drawing.point(20,40)
$inputBox.Font = "Microsoft Sans Serif,10"
 
# Labels
$label1 = New-Object system.windows.Forms.Label
$label1.Text = "  Type Directory View (e.g. C:\Windows)  "
$label1.BackColor = "#b41c1f"
$label1.AutoSize = $true
$label1.ForeColor = "#ffffff"
$label1.Width = 360
$label1.Height = 30
$label1.location = new-object system.drawing.point(20,10)
$label1.Font = "Microsoft Sans Serif,14"
 
$label3 = New-Object system.windows.Forms.Label
$label3.Text = "Select File Extension to view"
$label3.AutoSize = $true
$label3.Width = 360
$label3.Height = 30
$label3.location = new-object system.drawing.point(20,70)
$label3.Font = "Microsoft Sans Serif,14"
 
# Add controls to form
$Form.SuspendLayout()
$Form.Controls.Add($button1)
$Form.Controls.Add($button2)
$Form.Controls.Add($button3)
$Form.Controls.Add($button4)
$Form.Controls.Add($button5)
$Form.Controls.Add($button6)
$Form.Controls.Add($checkBox)
$Form.Controls.Add($label1)
$Form.Controls.Add($label2)
$Form.Controls.Add($label3)
$Form.Controls.Add($inputBox)
$Form.Controls.Add($outputBox)
$Form.Controls.Add($listBox)
$Form.ResumeLayout()
# Event handlers
$button6_Click = {
  foreach ($item in $listBox) {
    # Save listBox to Desktop
    $listBox.Items | Out-File $env:USERPROFILE\Desktop\ListBox.txt -Append
  }
  if ($checkBox = 'Checked') {
    $listBox.Items.Clear()
  }
}
 
<#
   ------------------------------------------------------------
   OutputBox Event Handler
   Allows 1 or more items to be selected and dragged to listBox
   ------------------------------------------------------------ #>
$outputBox_MouseDown = [System.Windows.Forms.MouseEventHandler] {
  $outputBox.DoDragDrop($outputBox.Text,[System.Windows.Forms.DragDropEffects]::Copy)
}
 
<#
   ----------------------------------------------------------------------------------
   ListBox Event Handlers
   Sets the only location a dragged item can enter.  In this case that is the ListBox
   ----------------------------------------------------------------------------------  #>
$listBox_DragEnter = [System.Windows.Forms.DragEventHandler] {
  $_.Effect = $_.AllowedEffect
}
 
<#
   ------------------------------------------------------------------------
   > Set how to drop selected item(s) into ListBox
   > Makes use of [System.IO.File] to read each line
     of a file, then add each line to the ListBox.
 
     Required to prevent multiple items from a multiline TextBox
     appearing as one long line inside ListBox, rather than a list of items
     ---------------------------------------------------------------------- #>
$listBox_DragDrop = [System.Windows.Forms.DragEventHandler] {
 
  # Read Temorary File back into ListBox
  [string[]] $lines =  [System.IO.File]::ReadAllLines("$env:USERPROFILE\Desktop\FilePath.txt")
  [string] $line
 
  foreach ($line in $lines) {
    $listBox.Text = $listBox.Items.Add($line)
  }
  # Clear OutputBox
  $outputBox.Clear()
 
  # Delete Temporary File
  Remove-Item "$env:USERPROFILE\Desktop\FilePath.txt"
}
 
$form_FormClosed = {
  try {
    $Form.remove_FormClosed($Form_Cleanup_FormClosed)
    $outputBox.remove_MouseDown($outputBox_MouseDown)
    $listBox.remove_DragEnter($listBox_DragEnter)
    $listBox.remove_DragDrop($listBox_DragDrop)
  }
  catch [Exception] {}
}
#Initialize Events
$Form.Add_Click($button6_Click)
$button1.Add_Click($button1_Click)
$button2.Add_Click($button2_Click)
$button3.Add_Click($button3_Click)
$button4.Add_Click($button4_Click)
$button5.Add_Click($button5_Click)
$button6.Add_Click($button6_Click)
$outputBox.Add_MouseDown($outputBox_MouseDown)
$listBox.Add_DragEnter($listBox_DragEnter)
$listBox.Add_DragDrop($listBox_DragDrop)
 
$Form.Add_FormClosed($Form_FormClosed)
 
# Initialize Form
[void]$Form.ShowDialog()
$Form.Dispose()
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
31.07.2019, 14:32
Помогаю со студенческими работами здесь

Ошибки Cannot send session cookie, Cannot send session cache limiter
Переустановил винду, поставил apache, старый конфиг подредактировал (поменял локальниный диск). Тут решил дописать остатки сайта,...

Ошибка при отправке e-mail (mailMessage), настройка SMTP
Мой первый сайт на ASP.NET на хостинге somee.com. Я делаю так, чтобы посетитель сайта мог отправить мне e-mail. В control panel хостинг...

Как использовать Прокси при отправке писем через MailMessage ?
Как использовать прокси при отправке письма через MailMessage ? (Использую в таком виде): MailMessage mail = new...

<input type="Image" name="send" src="send.gif"> - скрипт не работает
LUDI SCRIPT NE RABOTAET, GDE OSHIBKA. ESLI EST' PREDLOJENIYA NA JAVA SCRIPT NE OTKOJUS' &lt;html&gt; &lt;head&gt; &lt;SCRIPT language=VBScript&gt; ...

прописан формат сайта XHTML но написан по правилам HTML, поменять формат или переписывать код?
скажите пожалуйста что лучше сделать? validator.w3.org показывает кучу ошибок связанных с неправильно закрытыми тегами типа не &lt;br&gt; а...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
5
Ответ Создать тему
Новые блоги и статьи
YAFU@home — распределённые вычисления для математики. На CPU
Programma_Boinc 20.01.2026
YAFU@home — распределённые вычисления для математики. На CPU YAFU@home — это BOINC-проект, который занимается факторизацией больших чисел и исследованием aliquot-последовательностей. Звучит. . .
http://iceja.net/ математические сервисы
iceja 20.01.2026
Обновила свой сайт http:/ / iceja. net/ , приделала Fast Fourier Transform экстраполяцию сигналов. Однако предсказывает далеко не каждый сигнал (см ограничения http:/ / iceja. net/ fourier/ docs ). Также. . .
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь постоянного тока с R, L, C, k(ключ), U, E, J. Программа составляет систему уравнений по 1 и 2 законам Кирхгофа, решает её и находит: токи, напряжения и их 1 и 2 производные при t = 0;. . .
Восстановить юзерскрипты Greasemonkey из бэкапа браузера
damix 15.01.2026
Если восстановить из бэкапа профиль Firefox после переустановки винды, то список юзерскриптов в Greasemonkey будет пустым. Но восстановить их можно так. Для этого понадобится консольная утилита. . .
Сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11 Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru