-
Notifications
You must be signed in to change notification settings - Fork 0
/
Lib1.ps1
1754 lines (1532 loc) · 58 KB
/
Lib1.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
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function Get-DriveSpace
{
<#
.SYNOPSIS
This function prints capacity and free space in a drive.
.DESCRIPTION
This function prints the capacity and free space in any drive on any computer.
Gets this info via Get-WmiObject cmdlet, and checks connection to the remote computer
via Test-Connection beforehand.
.EXAMPLE
Get-DriveSpace
This command prints info about C: drive on local computer.
.EXAMPLE
Get-DriveSpace -deviceID=D:
This command prints info about D: drive on local computer.
.EXAMPLE
Get-DriveSpace -computername Server1
This command prints info about C: drive on remote computer server1
.EXAMPLE
Get-DriveSpace -computername Server1 -DeviceID D:
This command prints info about D: drive on remote computer server1
#>
[CmdletBinding()]
Param(
# Remote computer to be queried
[string]$ComputerName=$env:computername,
# Drive letter, ending with a colon.
[string]$deviceID='C:'
)
$bUp = Test-Connection -Quiet -Count 1 -ComputerName $ComputerName
if (($ComputerName -ne $env:computername -and $bUp) -or ($ComputerName -eq $env:computername))
{
Get-WmiObject -ComputerName $ComputerName -Class Win32_LogicalDisk -Filter "DeviceID='$deviceID'" |
select @{n="Host";e={$_.SystemName}}, @{n="FreeMB";e={"{0:N2}" -f ($_.Freespace / 1MB)}}, @{n="TotalMB";e={"{0:N2}" -f ($_.size/1MB)}}
}
elseif (!$bUp)
{
Write-Output "$computername is down"
}
}
function Get-MonitorInfo
{
<#
.SYNOPSIS
Prints info about the connected monitor.
.DESCRIPTION
This function uses Get-WmiObject cmdlet class WmiMonitorID for the currently connected screen(s),
and displays manufacturer, product code, serial number and production date info.
No ping test is made before WMI query.
.EXAMPLE
Get-MonitorInfo
Manufacturer : LGD
ProductCode : 032C
SerialNumber : 0
Name :
Week : 0
Year : 2011
Manufacturer : DEL
ProductCode : A088
SerialNumber : 2W2Y82BN1H3U
Name : DELL P1913
Week : 47
Year : 2012
This command gets info about the local machine's screens, where LGD is the laptop screen,
and DEL is the second monitor. Manufacturer codes are three-letter codes.
.EXAMPLE
Get-MonitorInfo -ComputerName pc1
This command gets info about remote computer PC1.
#>
[CmdletBinding()]
Param
(
[Parameter(
Position=0,
ValueFromPipeLine=$true,
ValueFromPipeLineByPropertyName=$true)]
[string]$ComputerName = '.'
)
Process
{
$ActiveMonitors = Get-WmiObject -Class WmiMonitorID -Namespace root\wmi -ComputerName $ComputerName
$Graphics = Get-WmiObject -ComputerName $ComputerName -Class Win32_VideoController
$monitorInfo = @()
foreach ($monitor in $ActiveMonitors)
{
$mon = New-Object PSObject
$manufacturer = $null
$product = $null
$serial = $null
$name = $null
$week = $null
$year = $null
$monitor.ManufacturerName | foreach {$manufacturer += [char]$_}
$monitor.ProductCodeID | foreach {$product += [char]$_}
$monitor.SerialNumberID | foreach {$serial += [char]$_}
$monitor.UserFriendlyName | foreach {$name += [char]$_}
$mon | Add-Member NoteProperty Manufacturer $manufacturer
$mon | Add-Member NoteProperty ProductCode $product
$mon | Add-Member NoteProperty SerialNumber $serial
$mon | Add-Member NoteProperty Name $name
$mon | Add-Member NoteProperty Week $monitor.WeekOfManufacture
$mon | Add-Member NoteProperty Year $monitor.YearOfManufacture
$monitorInfo += $mon
}
return $monitorInfo
}
}
function Get-Uptime
{
<#
.SYNOPSIS
This script will report uptime of given computer since last reboot.
.DESCRIPTION
Pre-Requisites: Requires PowerShell 2.0 and WMI access to target computers (admin access).
Queries WMI class Win32_OperatingSystem for LastBootUpTime value.
Usage syntax:
For local computer where script is being run: .\Get-Uptime.ps1.
For list of remote computers: .\Get-Uptime.ps1 -ComputerList "c:\temp\computerlist.txt"
Last Modified: 3/20/2012
Created by
Bhargav Shukla
http://blogs.technet.com/bshukla
http://www.bhargavs.com
Downloaded from Technet at May 27th, 2015 (Metin)
DISCLAIMER
==========
THIS CODE IS MADE AVAILABLE AS IS, WITHOUT WARRANTY OF ANY KIND. THE ENTIRE
RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS CODE REMAINS WITH THE USER.
Requires -Version 2.0
.EXAMPLE
Get-Uptime.ps1 -Computer ComputerName
Displays uptime of one remote computer
.EXAMPLE
Get-Uptime.ps1 -ComputerList "c:\temp\computerlist.txt" | Export-Csv uptime-report.csv -NoTypeInformation
Displays uptime of computers given in the computerlist.txt file, and exports them as csv file
#>
[CmdletBinding()]
param
(
[Parameter(Position=0,ValuefromPipeline=$true)][string][alias("cn")]$computer,
[Parameter(Position=1,ValuefromPipeline=$false)][string]$computerlist,
[switch]$FastBoot
)
If (-not ($computer -or $computerlist))
{
$computers = $Env:COMPUTERNAME
}
If ($computer)
{
$computers = $computer
}
If ($computerlist)
{
$computers = Get-Content $computerlist
}
foreach ($computer in $computers)
{
$Computerobj = "" | select ComputerName, Uptime, LastReboot
$now = Get-Date
if ($FastBoot) {
$boottime = (Get-WinEvent -ComputerName $computer -FilterHashtable @{Logname="System";Id=1;ProviderName="*Kernel-General"} | where {$_.properties[3].Value -eq 2} | Select-Object -First 1).TimeCreated
}
else {
$wmi = Get-WmiObject -ComputerName $computer -Query "SELECT LastBootUpTime FROM Win32_OperatingSystem"
$boottime = $wmi.ConvertToDateTime($wmi.LastBootUpTime)
}
$uptime = $now - $boottime
$d =$uptime.days
$h =$uptime.hours
$m =$uptime.Minutes
$s = $uptime.Seconds
$Computerobj.ComputerName = $computer
$Computerobj.Uptime = "$d Days $h Hours $m Min $s Sec"
$Computerobj.LastReboot = $boottime
$Computerobj
}
}
function Get-RebootInfo
{
<#
.SYNOPSIS
Get latest reboot events from the computer. This is the function that runs with Get-WinEvent.
.DESCRIPTION
Queries local or remote computer System event logs for boot (6005), shutdown (6006) or crash (6008) events
to list the last reboot information.
Use -NumberOfDays argument to search for required number of days past info.
Use -Computername parameter to point to a remote computer. RemoteRegistry service on the remote computer
is started to get this information.
This is the function that runs with Get-WinEvent cmdlet. The older method uses Get-EventLog cmdlet.
2018-01-08 Metin
.EXAMPLE
Get-RebootInfo
Get startup and shutdown events from the local computer from the last 30 days.
.EXAMPLE
Get-RebootInfo -NumberOfDas 10
Get startup and shutdown events from the local computer from the last 10 days.
.EXAMPLE
Get-RebootInfo -ComputerName server1
Get startup and shutdown events from remote computer server1, for the last 30 days.
.EXAMPLE
Get-RebootInfo -ComputerName server1 -NumberOfDays -60
Get startup and shutdown events from remote computer server1, for the last 60 days.
#>
[CmdletBinding()]
Param
(
[string]$ComputerName=$env:Computername,
[int]$NumberOfDays=30
)
# [timespan]$uptime = New-TimeSpan -start 0 -end 0
$currentTime = get-Date
$startUpID = 6005
$shutDownID = 6006
$crashID = 6008
$startingDate = (Get-Date -Hour 00 -Minute 00 -Second 00).adddays(-$numberOfDays)
$IsHostUp = $false
# $startingDate = Get-Date -Year 2016 -Month 1 -Day 1 -Hour 00 -Minute 00 -Second 00
# $endingDate = Get-Date -Year 2016 -Month 2 -Day 25 -Hour 00 -Minute 00 -Second 00
if ($ComputerName -eq $env:Computername)
{
$events = Get-WinEvent -FilterHashTable @{LogName="system";ID=$startUpID,$shutDownID,$crashID;StartTime=$startingDate}
$IsHostUp = $true
}
else
{
if (Test-Connection $ComputerName -Quiet -Count 1)
{
Write-Host "Host is up, fetching events..."
# below disabled @ 2023-05-31, looks like no need on Win11?
# Get-Service -ComputerName $ComputerName -Name RemoteRegistry | Start-Service
$events = Get-WinEvent -ComputerName $ComputerName -FilterHashTable @{LogName="system";ID=$startUpID,$shutDownID,$crashID;StartTime=$startingDate}
# canceled serivce stop @2017-01-11
# Get-Service -ComputerName $ComputerName -Name RemoteRegistry | Stop-Service
$IsHostUp = $true
}
else
{
Write-Host $ComputerName " appears to be down."
$IsHostUp = $false
}
}
if ($IsHostUp)
{
$i = $events.Count-1
$Table1 = New-Object System.Data.DataTable "UptimeList"
$Col1 = New-Object System.Data.DataColumn TimeCreated,([datetime])
$Col2 = New-Object System.Data.DataColumn EventType,([string])
$Col3 = New-Object System.Data.DataColumn Duration,([string])
$Table1.Columns.Add($Col1)
$Table1.Columns.Add($Col2)
$Table1.Columns.Add($Col3)
For($i=$events.Count-1; $i -ge 0; --$i)
{
$newrow = $Table1.NewRow()
$newrow.TimeCreated = $events[$i].TimeCreated
if ([int32]$events[$i].ID -eq 6005)
{
$newrow.EventType = "Startup"
$eventtype="uptime"
}
elseif ([int32]$events[$i].ID -eq 6006)
{
$newrow.EventType = "Shutdown"
$eventtype = "downtime"
}
elseif ([int32]$events[$i].ID -eq 6008)
{
$newrow.EventType = "-UNEXPECTED-"
if ($events[$i].LevelDisplayName -eq 'Hata') # if Turkish locale
{
$eventtype += "/ " + ($events[$i].Message).Substring(0,24)
}
else # if English locale
{
$eventtype += "/ " + ($events[$i].Message).Substring(31,28)
}
}
else
{
$newrow.EventType = "-unknown-"
$eventtype = "-unknown-"
}
if ($i -eq 0)
{
$Duration = (Get-Date) - $events[$i].TimeCreated
}
else
{
$Duration = $events[$i-1].TimeCreated - $events[$i].TimeCreated
}
$newrow.Duration = "$($Duration.Days) days, $($Duration.Hours) hours, $($Duration.Minutes) minutes, $($Duration.Seconds) seconds $eventtype"
$Table1.Rows.Add($newrow)
}
Write-Host "From host " $ComputerName ", starting from " $startingDate
$Table1 | ft "TimeCreated", "EventType", "Duration" -Autosize
}
}
function Get-HwInfo
{
<#
.SYNOPSIS
Get some key hardware info from a computer.
.DESCRIPTION
Queries the local or remote computer WMI for these information:
-CPU Info (manufacturer, name, cache sizes, clock speeds, ID)
-RAM Info (total RAM size, RAM speed, serial number, part numer)
for local computer. And for a remote computer gets these additional info:
-Sound Card
-Video Card
.EXAMPLE
Get-HwInfo
Host : LocalComputer
Caption : Intel64 Family 6 Model 58 Stepping 9
Manufacturer : GenuineIntel
Name : Intel(R) Core(TM) i5-3210M CPU @ 2.50GHz
L2CacheSize : 512
L3CacheSize : 3072
MaxClockSpeed: 2501
AddressWidth : 64
DataWidth : 64
ProcessorId : BFEBFBFF000306A9
Cores : 2
Logical CPUs : 4
Total RAM : 8192 MB
RAM DataWidth: 64
RAM Speed : 1600
RAM SerialNo : F2312666
RAM PartNum : NT8GC64B8HB0NS-DI
.EXAMPLE
Get-HwInfo -ComputerName server
Host : server
Caption : Intel64 Family 6 Model 58 Stepping 9
Manufacturer : GenuineIntel
Name : Intel(R) Core(TM) i5-3210M CPU @ 2.50GHz
L2CacheSize : 512
L3CacheSize : 3072
MaxClockSpeed: 2501
AddressWidth : 64
DataWidth : 64
ProcessorId : BFEBFBFF000306A9
Cores : 2
Logical CPUs : 4
Total RAM : 8192 MB
RAM DataWidth: 64
RAM Speed : 1600
RAM SerialNo : 76352669
RAM PartNum : NT8GC64B8HB0NS-DI
Sound Device Name : IDT High Definition Audio CODEC
Sound Device Manufacturer : IDT
Sound Device Name : Intel(R) Ekran Icin Ses
Sound Device Manufacturer : Intel(R) Corporation
Graphics Card Name : Current Display Controller Configuration
Video Mode : 1024 by 768 pixels, True Color, 60 Hertz
#>
[CmdletBinding()]
param (
[string]$ComputerName=$env:Computername
)
$HostUpAndRunning = $false
if (Test-Connection $ComputerName -Quiet -Count 1) # seperate definitions for local and remote mode all unified
{
$chasistype = Get-WmiObject -ComputerName $ComputerName -Class win32_SystemEnclosure
$arrChasistypes = ("Other","Unknown","Desktop","Low Profile Desktop","Pizza Box","Mini Tower","Tower","Portable","Laptop","Notebook","Handheld","Docking Station","All-in-One","Sub-Notebook","Space Saving","Lunch Box","Main System Chassis","Expansion Chassis","Sub-Chassis","Bus Expansion Chassis","Peripheral Chassis","Storage Chassis","Rack Mount Chassis","Sealed-Case PC")
$sCPU =Get-WmiObject -ComputerName $ComputerName -class win32_processor
$oMem = Get-WmiObject -ComputerName $ComputerName -class Win32_PhysicalMemory
$oAu = Get-WmiObject -ComputerName $ComputerName -class Win32_SoundDevice
# $oGr = Get-WmiObject -class Win32_DisplayControllerConfiguration -ComputerName $ComputerName
# replaced by the following line [2017-10-16]
$oGr = Get-WmiObject -ComputerName $ComputerName -Class Win32_VideoController
$net = Get-WmiObject -ComputerName $ComputerName -Class win32_networkadapter | where {$_.NetConnectionStatus -ge 0}
$arrNetconstat = ("Disconnected","Connecting","Connected","Hardware not present","Hardware Disabled","Hardware Malfunction","Media Disconnected","Authenticating","Authentication Required","Authentication Succeede","Authentication Failed","Invalid Address","Credentials Required")
$HostUpAndRunning = $true
}
else
{
Write-Host $ComputerName " is down."
$HostUpAndRunning = $false
}
if ($HostUpAndRunning)
{
Write-Host "Host : " $ComputerName
foreach ($sProperty in $chasistype.ChassisTypes)
{
Write-host("Enclosure Type : " + $arrChasistypes[$sProperty-1]) -ErrorAction SilentlyContinue
}
# CPU Info
Write-Output "========= CPU ========="
foreach($sProperty in $sCPU)
{
write-host "Caption : " $sProperty.Caption
write-host "Manufacturer : " $sProperty.Manufacturer
write-host "Name : " $sProperty.Name
write-host "L2CacheSize : " $sProperty.L2CacheSize
write-host "L3CacheSize : " $sProperty.L3CacheSize
write-host "MaxClockSpeed: " $sProperty.MaxClockSpeed
write-host "AddressWidth : " $sProperty.AddressWidth
write-host "DataWidth : " $sProperty.DataWidth
write-host "ProcessorId : " $sProperty.ProcessorId
write-host "Cores : " $sProperty.NumberOfCores
write-host "Logical CPUs : " $sProperty.NumberOfLogicalProcessors
}
# Memory Info
Write-Output "======= Memory ========"
foreach($sProperty in $oMem)
{
Write-Host("Total RAM : " + ($sProperty.Capacity)/1024/1024 + " MB")
Write-Host "RAM DataWidth: " $sProperty.DataWidth
Write-Host "RAM Speed : " $sProperty.Speed
Write-Host "RAM SerialNo : " $sProperty.SerialNumber
Write-Host "RAM PartNum- : " $sProperty.PartNumber
}
# SoundCard Info
Write-Output "======== SOUND ========"
foreach($sProperty in $oAu)
{
Write-Host("Sound Device Name : " + $sProperty.Caption)
Write-Host("Sound Device Manufacturer : " + $sProperty.Manufacturer)
}
# Graphics Card Info
Write-Output "====== GRAPHICS ======="
foreach($sProperty in $oGr)
{
Write-Host("Graphics Card Name : " + $sProperty.Caption)
Write-Host("Video Mode : " + $sProperty.VideoModeDescription)
}
# Network Adapter Info
Write-Output "========= NET ========="
foreach ($sProperty in $net)
{
Write-Host( $sProperty.netconnectionid + " adaptor : " + ($sProperty.Name) + " - " + $sProperty.MACAddress + " - (" + $arrNetconstat[$sProperty.NetConnectionStatus] + ")")
}
}
}
function Get-OSInfo
{
<#
.SYNOPSIS
Get OS info from a computer.
.DESCRIPTION
Queries WMI win32_OperatingSystem object for these fields:
- Host Description
- OS Caption
- OS Version
- OS architecture (32-bit / 64-bit)
- Build Number
- SP major version
- OS installed date-time
Ping test is done beforehand.
.EXAMPLE
Get-OSInfo -ComputerName server
Host : server
Description :
Caption : Microsoft Windows 7 Professional
Version : 6.1.7601
Architecture: 64-bit
BuildNumber : 7601
SP Major v. : 1
Installed on: 18.02.2013 21:12:54
Lookup : https://en.wikipedia.org/wiki/Windows_10_version_history#Version_2004_(May_2020_Update)
#>
[CmdletBinding()]
param (
[string]$ComputerName=$env:Computername
)
$HostUpAndRunning = $false
if ($ComputerName -eq $env:Computername)
{
$sOS =Get-WmiObject -class Win32_OperatingSystem
$HostUpAndRunning = $true
}
else
{
if (Test-Connection $ComputerName -Quiet -Count 1)
{
$sOS =Get-WmiObject -class Win32_OperatingSystem -computername $ComputerName
$HostUpAndRunning = $true
}
else
{
Write-Host $ComputerName " is down."
$HostUpAndRunning = $false
}
}
if ($HostUpAndRunning)
{
# Write-Host "Host : " $ComputerName
foreach($sProperty in $sOS)
{
if ($sProperty.Caption -like "*Windows 10*")
{
$BuildNumber = [int]($sProperty.BuildNumber)
# if ($BuildNumber -ge 20190)
# {
# $VersionNumber = 2104
# }
# elseif ($BuildNumber -ge 19042)
# {
# $VersionNumber = 2009
# }
# elseif ($BuildNumber -ge 19041)
# {
# $VersionNumber = 2004
# }
# elseif ($BuildNumber -ge 18363)
# {
# $VersionNumber = 1909
# }
# elseif ($BuildNumber -ge 18362)
# {
# $VersionNumber = 1903
# }
# elseif ($BuildNumber -ge 17763)
# {
# $VersionNumber = 1809
# }
# elseif ($BuildNumber -ge 17134)
# {
# $VersionNumber = 1803
# }
# elseif ($BuildNumber -ge 16299)
# {
# $VersionNumber = 1709
# }
# elseif ($BuildNumber -ge 15063)
# {
# $VersionNumber = 1703
# }
# elseif ($BuildNumber -ge 14393)
# {
# $VersionNumber = 1607
# }
# elseif ($BuildNumber -ge 10586)
# {
# $VersionNumber = 1511
# }
# else # BuildNumber = 10240
# {
# $VersionNumber = 1507
# }
}
$datetimeformat = ([WMI] '').ConvertToDateTime($sProperty.InstallDate)
$obj = @{ Host = $ComputerName
Description = $sProperty.Description
Caption = $sProperty.Caption
Version = $sProperty.Version
Architecture = $sProperty.OSArchitecture
BuildNumber = $sProperty.BuildNumber
SPMajorVersion = $sProperty.ServicePackMajorVersion
InstalledOn = $datetimeformat
}
$obj
# write-host "Description : " $sProperty.Description
# write-host "Caption : " $sProperty.Caption
# if ($sProperty.Caption -like "*Windows 10*")
# {
# Write-Host "Win10Version: " $VersionNumber
# }
# write-host "Version : " $sProperty.Version
# write-host "Architecture: " $sProperty.OSArchitecture
# write-host "BuildNumber : " $sProperty.BuildNumber
# write-host "SP Major v. : " $sProperty.ServicePackMajorVersion
# # bu bi yontem $datetimeformat = [datetime]::ParseExact($sProperty.InstallDate.SubString(0,14),"yyyyMMddhhmmss",$null)
# write-host "Installed on: " $datetimeformat
}
}
}
function Get-BiosParams
{
<#
.SYNOPSIS
Gets information about BIOS from a computer.
.DESCRIPTION
Queries the local or remote computer WMI win32_BIOS object for these info:
-BIOS Version
-BIOS Manufacturer
-BIOS Name
-BIOS Serial Number
-BIOS Version
Ping test is done beforehand.
.EXAMPLE
Get-BiosParams -ComputerName server
Host : server
SMBIOSBIOSVersion : A07
Manufacturer : Dell Inc.
Name : BIOS Date: 10/08/12 19:55:01 Ver: A07.00
SerialNumber : 97PQBW1
Version : DELL - 1072009
#>
[CmdletBinding()]
Param(
$ComputerName=$env:COMPUTERNAME
)
if ($ComputerName -eq $env:Computername)
{
Write-Host "Host : " $ComputerName
Get-WmiObject -Class Win32_bios
}
else
{
if (Test-Connection $ComputerName -Quiet -Count 1)
{
Write-Host "Host : " $ComputerName
Get-WmiObject -Class Win32_bios -ComputerName $ComputerName
}
else
{
Write-Host $ComputerName " is closed"
}
}
}
function Get-Lockouts
{
<#
.SYNOPSIS
This cmdlet, unlike its orignal one below, is more simple, more
to-the-point. Takes a list of domain controllers, queries their
security event logs for lockout events and bad login attempts
and displays them in list form.
.DESCRIPTION
If no argument is given, it is assumed that the last 1 hour period
is to be queried. If one argument is given, it has to be a username
argument and security logs are queried that contains this username
for 4740 (lockout), 4771 (kerberos pre-auth failed) and
4625 (bad login attempt) events.
.EXAMPLE
Below command queries 4740, 4771 and 4625 events in all DCs in the
domain for the last hour
Get-Lockouts
.EXAMPLE
Below command queries 4740, 4771 and 4625 events in all DCs and
filters them for user "ali.kurt"
Get-Lockouts ali.kurt
.EXAMPLE
Below example queries for any user account for the last 8 hours
Get-Lockouts -Username ali.kurt -Duration 8
#>
param(
[string]$UserName,
[int]$Duration=1,
[int]$Type=1
)
$domain = [System.Directoryservices.Activedirectory.Domain]::GetCurrentDomain()
if ($Type=1)
{
$eventlist = 4740
}
else {
$eventlist = (4740,4625,4771)
}
$resultevents = @()
if ($UserName)
{
$domain.DomainControllers.Name | ForEach-Object {
$ev = Get-WinEvent -ComputerName $_ -FilterHashtable @{LogName="Security";Id=$eventlist;StartTime=(Get-Date).AddHours(-$Duration)} | Where-Object { $PSItem.Message -match $UserName }
$resultevents += $ev
}
}
else
{
$domain.DomainControllers.Name | ForEach-Object {
$ev = Get-WinEvent -ComputerName $_ -FilterHashtable @{LogName="Security";Id=$eventlist;StartTime=(Get-Date).AddHours(-$Duration)}
$resultevents += $ev
}
}
$resultevents
}
function Get-LockoutLocation
{
<#
.SYNOPSIS
Taken from
https://blogs.technet.microsoft.com/poshchap/2014/05/16/tracing-the-source-of-account-lockouts/
Returns the location of last lockout cases (within last 1 hour, written in miliseconds).
.DESCRIPTION
within last 1 hour, if any lockouts are happend, this function returns the date and time they occured,
name of the account and the device on which lockout happened. Primary DC is automatically queried.
.PARAMETER UserName
This is a mandatory parameter. If not supplied, a prompt will ask for one. If not given, simply
it will not run.
.EXAMPLE
Get-LockoutLocation -UserName 'sedat.senisler'
#>
param(
[Parameter(Mandatory=$true)][string]$UserName
)
$PDC = Get-ADDomainController -Discover -Service PrimaryDC
Get-WinEvent -ComputerName $PDC -Logname Security `
-FilterXPath "*[System[EventID=4740 and TimeCreated[timediff(@SystemTime) <= 3600000]] and EventData[Data[@Name='TargetUserName']='$UserName']]" |
Select-Object TimeCreated,@{Name='User Name';Expression={$_.Properties[0].Value}},@{Name='Source Host';Expression={$_.Properties[1].Value}}
}
Function Get-FileMetaData
{
# -----------------------------------------------------------------------------
# Script: Get-FileMetaDataReturnObject.ps1
# Author: ed wilson, msft
# Date: 01/24/2014 12:30:18
# Keywords: Metadata, Storage, Files
# comments: Uses the Shell.APplication object to get file metadata
# Gets all the metadata and returns a custom PSObject
# it is a bit slow right now, because I need to check all 266 fields
# for each file, and then create a custom object and emit it.
# If used, use a variable to store the returned objects before attempting
# to do any sorting, filtering, and formatting of the output.
# To do a recursive lookup of all metadata on all files, use this type
# of syntax to call the function:
# Get-FileMetaData -folder (gci e:\music -Recurse -Directory).FullName
# note: this MUST point to a folder, and not to a file.
# -----------------------------------------------------------------------------
<#
.SYNOPSIS
This function gets file metadata and returns it as a custom PS Object
.DESCRIPTION
This function gets file metadata using the Shell.Application object and
returns a custom PSObject object that can be sorted, filtered or otherwise
manipulated.
.EXAMPLE
Get-FileMetaData -folder "e:\music"
Gets file metadata for all files in the e:\music directory
.Example
Get-FileMetaData -folder (gci e:\music -Recurse -Directory).FullName
This example uses the Get-ChildItem cmdlet to do a recursive lookup of
all directories in the e:\music folder and then it goes through and gets
all of the file metada for all the files in the directories and in the
subdirectories.
.EXAMPLE
Get-FileMetaData -folder "c:\fso","E:\music\Big Boi"
Gets file metadata from files in both the c:\fso directory and the
e:\music\big boi directory.
.EXAMPLE
$meta = Get-FileMetaData -folder "E:\music"
This example gets file metadata from all files in the root of the
e:\music directory and stores the returned custom objects in a $meta
variable for later processing and manipulation.
.Parameter Folder
The folder that is parsed for files
.Notes
NAME: Get-FileMetaData
AUTHOR: ed wilson, msft
LASTEDIT: 01/24/2014 14:08:24
KEYWORDS: Storage, Files, Metadata
HSG: HSG-2-5-14
.Link
Http://www.ScriptingGuys.com
#Requires -Version 2.0
#>
Param([string[]]$folder)
foreach($sFolder in $folder)
{
$a = 0
$objShell = New-Object -ComObject Shell.Application
$objFolder = $objShell.namespace($sFolder)
foreach ($File in $objFolder.items())
{
$FileMetaData = New-Object PSOBJECT
for ($a ; $a -le 266; $a++)
{
if($objFolder.getDetailsOf($File, $a))
{
$hash += @{$($objFolder.getDetailsOf($objFolder.items, $a)) =
$($objFolder.getDetailsOf($File, $a)) }
$FileMetaData | Add-Member $hash
$hash.clear()
} #end if
} #end for
$a=0
$FileMetaData
} #end foreach $file
} #end foreach $sfolder
} #end Get-FileMetaData
function Get-RebootReason
{
<#
.Synopsis
Tries to get reason about the shutdown / reboot.
.DESCRIPTION
Queries the [remote] computer's system log using Get-WinEvent with event
codes 41, 109, 1001, 1074, 1076, 6005, 6006, 6008.
.EXAMPLE
Example of how to use this cmdlet
.EXAMPLE
Another example of how to use this cmdlet
#>
Param
(
# Computer to be queried
[Parameter(ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
ValueFromRemainingArguments=$false,
Position=0)]
[string]$ComputerName=$env:COMPUTERNAME,
# StartTime that the query starts from, defaults to 3 days ago.
$StartTime = (Get-Date).AddDays(-3),
# Endtime defaults to now + 1 hour
$EndTime = (Get-Date).AddHours(1)
)
Get-WinEvent -ComputerName $ComputerName -FilterHashTable @{LogName='System';StartTime=$StartTime;EndTime=$EndTime;ID=41,109,1001,1074,1076,6005,6006,6008}
}
function Get-MemoryConsumed
{
<#
.Synopsis
Find amount of memory a process consumes.
.DESCRIPTION
By default calculates how much private bytes totally a process (or processes, given by -ProcessName property)
totally consumes.
Private bytes is the total amount of virtual memory allocated to the process (some of which may be on swap),
except shared memory, where as working set the the amount of RAM it occupies together with shared allocations.
Private Working set is the amount it occupies in RAM except shared memory.
Possible values for PSField :
- PrivateMemorySize/64 (default) :
- WorkingSet
- VirtualMemorySize/64 (-removed-)
- MaxWorkingSet (-removed-)
- MinWorkingSet (-removed-)
- NonpagedSystemMemorySize/64
- PagedMemorySize/64
- PagedSystemMemorySize/64
- PeakPagedMemorySize/64
- PeakVirtualMemorySize (-removed-)
- PeakWorkingSet
Metin, 2018-03-08
.EXAMPLE
Get-MemoryConsumed -ProcessName firefox
#>
Param
(
[Parameter(Mandatory=$true)][string]$ProcessName,
[ValidateSet("PrivateMemorySize","PrivateMemorySize64","WorkingSet","NonpagedSystemMemorySize","NonpagedSystemMemorySize64","PagedMemorySize","PagedMemorySize64","PagedSystemMemorySize","PagedSystemMemorySize64","PeakPagedMemorySize","PeakPagedMemorySize64","PeakWorkingSet")]
[string]$PSField = "PrivateMemorySize"
)
$pslist = get-process -Name $Processname -ErrorAction SilentlyContinue | select $PSField
$numps = (gps $ProcessName).Length
$MemSum = ($pslist.$PSField | Measure-Object -Sum).Sum
write-Output([string]($numps) + " processes")
Write-Output("{0:N0}" -f $MemSum + " Bytes")
Write-Output("{0:N0}" -f [int]($MemSum/1024/1024) + " MB")
}
function Get-LongNames
{
<#
.Synopsis
Finds files with long path+file names.
.DESCRIPTION
Queries the folder given by the -Path parameter and it subfolders for long file+path names
longer than limit given by the -Threshold parameter.
Metin 2018-05-22
.EXAMPLE
Get-Longnames -Path D:\tools -Threshold 200
#>
Param(
[Parameter(Mandatory=$true)][string]$Path,
[int]$Threshold=200
)
Get-ChildItem -Path $Path -Recurse | foreach { if (($_.FullName).Length -gt $Threshold) {Write-Host ($_.FullName).Length, $_.DirectoryName }}
}
function Get-PageTime
{
<#
.SYNOPSIS
Measures loading time of a web page.
.DESCRIPTION
Tries to connect to the address given by the -URL parameter, number of -Times times
and displays the results.
Don't forget to use http or https in front of the url.
Taken from:
https://blogs.technet.microsoft.com/fromthefield/2013/07/22/using-powershell-to-measure-page-download-time/
Metin, 2018-05-26
.EXAMPLE
Get-PageTime -url http://www.ozmener.net -times 10
#>
param($URL, $Times)
$i = 0
While ($i -lt $Times)
{
$Request = New-Object System.Net.WebClient
$Request.UseDefaultCredentials = $true
$Start = Get-Date
$PageRequest = $Request.DownloadString($URL)
$TimeTaken = ((Get-Date) - $Start).TotalMilliseconds
$Request.Dispose()
Write-Host Request $i took $TimeTaken ms -ForegroundColor Green
$i ++
}
}
function Play-Sound
{
<#
.SYNOPSIS
Play a sound to draw attention.
.DESCRIPTION
This function by default plays a notification sound to draw attention.
-Play argument can be used to play arbitrary sound file. It must be a waveform file.