Wednesday, October 31, 2018

Scary Tools - Delete locked file or folder utilities

Delete a locked file and folder utilities below. However, you must run each app by right-click and run as Administrator. These apps will delete file or folder that your account does not have permissions to, but your account must be part of Administrators group. 

It's a quick way to delete locked files, without having to change permissions on the file or folder.

























  1. http://bit.ly/DeleteLockedFile
  2. http://bit.ly/DeleteLockedFolder

Friday, October 26, 2018

Fix "There is no script engine for file extension '.js'" Visual Studio Post Build Event

Fix "There is no script engine for file extension '.js'" Visual Studio 2010 Post Build Event

1
cscript.exe $(ProjectDir)EnableLaunchApplication.js $(BuiltOuputPath)

Solution add /e:javascript to cmd line

1
cscript.exe /e:javascript $(ProjectDir)EnableLaunchApplication.js $(BuiltOuputPath)

Wednesday, October 24, 2018

How to Out of Chrome Browser Automatic Logins

“A few weeks ago, Google shipped an update to Chrome that fundamentally changes the sign-in experience,” Green wrote in a blog post. “From now on, every time you log into a Google property (for example, Gmail), Chrome will automatically sign the browser into your Google account for you. It’ll do this without asking, or even explicitly notifying you. (However, and this is important: Google developers claim this will not actually start synchronizing your data to Google — yet.)” 

The bad news is you have to opt out of automatic logins rather than opt into it.

How to Disable Automatic Login in Chrome 70+

To disable the controversial Chrome feature, first you have to update to Chrome 70. This will happen in the background automatically in the coming days, but you can also force the update simply by going to the “About Chrome” page in the menu bar. Once you update, opt out of automatic logins by opening Chrome’s settings page and scrolling to (or searching for) “Allow Chrome sign-in.” Once you find it, slide the toggle to off and you’re all set.





























Source : https://bgr.com/2018/10/17/chrome-70-update-released-disable-automatic-login/



Monday, October 22, 2018

jQuery File Upload Plugin broken for 8 year - open source equals open quality

A recent bug the massively popular jQuery File Upload widget and allowed an attacker to upload arbitrary files on web servers, including command shells for sending out commands for past 8 yrs, was recent corrected. 

According to Bleeping Computer, "
There are over 7,800 variations at the moment, and Cashdollar says that there are cases where the vulnerability exists even if the original code was modified to meet custom needs."




















This again puts the quality of open source projects into the spotlight. And now with the quality of Windows Update massively under-performing using this approach, there has to be a rethink. You pay for what you get. User beware.

Sunday, October 21, 2018

C# .NET Bug - Environment.CurrentDirectory does not work with escalated privileges

In a arduous session to figure out some production code, I have discovered that Environment.CurrentDirectory does not work in when running with elevated privileges.

Specifically if you set app.config to get your app to run as Administrator with UAC prompt
 <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
this will return the location of the exe, not the current directory the exe is run from.

Super frustrating and a bug in .NET.

Here's the simple source code


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestExe
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Environment.CurrentDirectory);
            Console.Read();
        }
    }
}

Here's app.config code


 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
<?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <!-- UAC Manifest Options
            If you want to change the Windows User Account Control level replace the 
            requestedExecutionLevel node with one of the following.

        <requestedExecutionLevel  level="asInvoker" uiAccess="false" />
        <requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />
        <requestedExecutionLevel  level="highestAvailable" uiAccess="false" />

            Specifying requestedExecutionLevel node will disable file and registry virtualization.
            If you want to utilize File and Registry Virtualization for backward 
            compatibility then delete the requestedExecutionLevel node.
        -->
        <requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />
      </requestedPrivileges>
    </security>
  </trustInfo>

  <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
    <application>
      <!-- A list of all Windows versions that this application is designed to work with. 
      Windows will automatically select the most compatible environment.-->

      <!-- If your application is designed to work with Windows Vista, uncomment the following supportedOS node-->
      <!--<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}"></supportedOS>-->

      <!-- If your application is designed to work with Windows 7, uncomment the following supportedOS node-->
      <!--<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>-->

      <!-- If your application is designed to work with Windows 8, uncomment the following supportedOS node-->
      <!--<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"></supportedOS>-->

      <!-- If your application is designed to work with Windows 8.1, uncomment the following supportedOS node-->
      <!--<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>-->

    </application>
  </compatibility>

  <!-- Enable themes for Windows common controls and dialogs (Windows XP and later) -->
  <!-- <dependency>
    <dependentAssembly>
      <assemblyIdentity
          type="win32"
          name="Microsoft.Windows.Common-Controls"
          version="6.0.0.0"
          processorArchitecture="*"
          publicKeyToken="6595b64144ccf1df"
          language="*"
        />
    </dependentAssembly>
  </dependency>-->

</asmv1:assembly>


Here's output running TestExe.exe from the c:\windows\system32 directory

Thursday, October 18, 2018

Powershell - Get all Windows file extensions from registry at HKEY_CLASSES_ROOT

























Here's a Powershell script to traverse all the keys in the registry at HKEY-CLASSES-ROOT to get all Windows file extensions that start with a dot. 


 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
#============================================================================================================================================================ 
# AUTHOR:         metadataconsult@gmail.com 
# WEBSITE:        http://metadataconsulting.blogspot.com 
# 
# SCRIPT NAME:    GetAllFileExtensions.ps1   
# DATE:           17/10/2018  
# VERSION:        1.0.0.0
# 
# SYNPOSIS:       Get all file extensions from registry at HKEY_CLASSES_ROOT  
#
#============================================================================================================================================================ 

#set HKCR hack
New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT
$i=0
Get-ChildItem 'HKCR:\' | ForEach-Object {  

 If($_.name -Match "^HKEY_CLASSES_ROOT\\\..+") {
    $i++
    Write-Host  $_.Name.Replace("HKEY_CLASSES_ROOT\","")
 }

}
"$i file extensions in Registry @ HKEY_CLASSES_ROOT\"


$i=0
Get-ChildItem 'HKLM:\Software\Classes\' | ForEach-Object {  
 
 If($_.name -Match "^HKEY_LOCAL_MACHINE\\Software\\Classes\\\..+") {
    $i++
    Write-Host  $_.Name.Replace("HKEY_LOCAL_MACHINE\Software\Classes\","")
 }

}
"$i file extensions in Registry @ HKEY_LOCAL_MACHINE\Software\Classes\"

$i=0
Get-ChildItem 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\' | ForEach-Object {  
 
 If($_.name -Match "^HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\\..+") {
    $i++
    Write-Host  $_.Name.Replace("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\","")
 }

}
"$i file extensions in Registry @ HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\"

My other Powershell scripts

Tuesday, October 16, 2018

Apple Phishing Email - Re: RE : [ Attentions Report Session ] [ Reminder Supports ] Your Details Accounts Has Been Locked Sessions

For the record, this is an Apple phishing email attempt that is recently going around and made it through spam filters. What to do?  Report them, goto bottom of page.


From : Apple Support 


Subject
 :
Re: RE : [ Attentions Report Session ] [ Reminder Supports ] Your Details Accounts Has Been Locked Sessions



It contains infected DOCX file: Apple-SupportIDAlert-ID1.8.docx

PHISHING LINKs;  

1. https://lihi.cc/iEPYq expands to -> https://secureserviced.serveirc.com/Auths

How to tell this is a Phishing email ?

  1. Check email address in full, if it's not from originating company then it's phishing.
  2. Hover over all links in email, if it's not from the apple.com site then forget it.

  3. The best way is to look at message source, see below.

How to examine Email Message Source ?

Now lets look at message source
  1. Outlook.com->Actions->View Message Source. 
  2. Gmail.com->More (down arrow to top right)->Show original.
Check for suspicious links, anything that does not originate from apple.com.


Report Phishing Email (not as Spam)

  1. Outlook.com->Junk (at Top)->Phishing Scam
  2. Gmail.com->More (downarrow to top right)->Report Phishing 

Report Phishing URLs at Google now 

If you have recievied this email take further action now by click these links

  1. https://www.google.com/safebrowsing/report_phish/


Report phishing at Microsoft and government agencies

  1. http://www.microsoft.com/security/online-privacy/phishing-faq.aspx

Report phishing emails to Apple 

Forward the email to abuse@icloud.com. This provides Apple's legal department and law enforcement with useful information to help prevent future phishing emails.

Monday, October 15, 2018

Apple Phishing Email - Re: [New Statement] We Have sent notification the last information issued your Apple Password was updated.

For the record, this is an Apple phishing email attempt that is recently going around and made it through spam filters. What to do?  Report them, goto bottom of page.


From : Apple Support

Subject
 : 
Re: [New Statement] We Have sent notification the last information issued your Apple Password was updated.



This Apple lD has been locked for security reasons.

Verification is required before 24 hours to get re-access your account. We have under maintenance service to improve our system to protect your account.

Please updated your account on https://appleid.apple.com/support.verification-account -- PHISHING LINK


Sincerely,

 
Apple Support


PHISHING LINKs;  

1. https://pxlme.me/sHYbt7Jx

How to tell this is a Phishing email ?

  1. Check email address in full, if it's not from originating company then it's phishing.
  2. Hover over all links in email, if it's not from the apple.com site then forget it.

  3. The best way is to look at message source, see below.

How to examine Email Message Source ?

Now lets look at message source
  1. Outlook.com->Actions->View Message Source. 
  2. Gmail.com->More (down arrow to top right)->Show original.
Check for suspicious links, anything that does not originate from apple.com.


Report Phishing Email (not as Spam)

  1. Outlook.com->Junk (at Top)->Phishing Scam
  2. Gmail.com->More (downarrow to top right)->Report Phishing 

Report Phishing URLs at Google now 

If you have recievied this email take further action now by click these links

  1. https://www.google.com/safebrowsing/report_phish/


Report phishing at Microsoft and government agencies

  1. http://www.microsoft.com/security/online-privacy/phishing-faq.aspx

Report phishing emails to Apple 

Forward the email to abuse@icloud.com. This provides Apple's legal department and law enforcement with useful information to help prevent future phishing emails.

Friday, October 12, 2018

Google hides huge hack of Google+ Social Network 500K accounts

"Do no evil" was a long time mission statement quietly removed under Sundar Pichai rule, for good reason.  Chief Executive Sundar Pichai was briefed on the plan not to notify users after an internal committee had reached that decision. A perfectly round figure itself is suspect so the actual amount may not be ever known.

"Google exposed the private data of hundreds of thousands of users of the Google+ social network and then opted not to disclose the issue this past spring, in part because of fears that doing so would draw regulatory scrutiny and cause reputational damage, according to people briefed on the incident and documents reviewed by The Wall Street Journal.

As part of its response to the incident, the Alphabet Inc. unit on Monday announced a sweeping set of data privacy measures that include permanently shutting down all consumer functionality of Google+. The move effectively puts the final nail in the coffin of a product that was launched in 2011 to challenge Facebook Inc. and is widely seen as one of Google’s biggest failures.

A software glitch in the social site gave outside developers potential access to private Google+ profile data between 2015 and March 2018, when internal investigators discovered and fixed the issue, according to the documents and people briefed on the incident. A memo reviewed by the Journal prepared by Google’s legal and policy staff and shared with senior executives warned that disclosing the incident would likely trigger “immediate regulatory interest”.

The closure of Google+ is part of a broader review of privacy practices by Google that has determined the company needs tighter controls on several major products, the people said. In its announcement Monday, the company said it is curtailing the access it gives outside developers to user data on Android smartphones and Gmail."

Source: https://www.wsj.com/articles/google-exposed-user-data-feared-repercussions-of-disclosing-to-public-1539017194

Wednesday, October 10, 2018

C# Round Datetime Extension To Nearest Minute And Smaller Units Are Rounded To Zero



C# D
ateTime extensions that rounds a datetime Up, Down or Nearest minutes and smaller units are rounded to zero.




 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
using System;
     
public static class Program
{
 /// <summary>
 /// Rounds datetime up, down or to nearest minutes and all smaller units to zero
 /// </summary>
 /// <param name="dt">ignore, implicitly passed</param>
 /// <param name="rndmin">mins to round to</param>
 /// <param name="directn">Up,Down,Nearest</param>
 /// <returns>rounded datetime with all smaller units than mins rounded off</returns>
 public static DateTime RoundToNearestMinuteProper(this DateTime dt, int rndmin, RoundingDirection directn)
 {
   if (rndmin == 0) //can be > 60 mins
   return dt;
  
   TimeSpan d = TimeSpan.FromMinutes(rndmin); //this can be passed as a parameter, or use any timespan unit FromDays, FromHours, etc.  
  
   long delta = 0;
   Int64 modTicks = dt.Ticks % d.Ticks;
  
   switch (directn)
   {
    case RoundingDirection.Up:
       delta = (modTicks != 0) ? d.Ticks - modTicks : 0;
    break;
    case RoundingDirection.Down:
       delta = -modTicks; 
    break;
    case RoundingDirection.Nearest:
    {
       bool roundUp = modTicks > (d.Ticks / 2);
       var offset = roundUp ? d.Ticks : 0;
       delta = offset - modTicks; 
       break;
    }
   
   }
   return new DateTime(dt.Ticks + delta, dt.Kind); 
 }
 
 public enum RoundingDirection
 {
  Up,
  Down,
  Nearest
 }
 
 public static void Main()
 {
  //var dt = new DateTime(2001, 1, 1, 0, 0, 0, 000);
  //var dt = new DateTime(2018, 08, 03, 10, 7, 30, 000); //8/3/2018 10:00:00 AM Nearest, re 15/2 = 7.5 mins or 7 mins and 30 secs
  var dt = new DateTime(2018, 08, 03, 10, 7, 31, 000); //8/3/2018 10:15:00 AM Nearest
  
  Console.WriteLine(dt.RoundToNearestMinuteProper(15, RoundingDirection.Up)); 
  Console.WriteLine(dt.RoundToNearestMinuteProper(15, RoundingDirection.Down)); 
  Console.WriteLine(dt.RoundToNearestMinuteProper(15, RoundingDirection.Nearest)); 
 }
}

Thursday, October 4, 2018

Powershell - Simple System Info - The One Liner Version 2 includes HD RPM and GPU info










This Powershell script boils down essential system information into 1 line for a post, quote or tweet. 


Example outputs; 
  1. Microsoft Windows 10 Pro 1803 (10.0.17134.320), Intel Core i7-2760QM CPU @ 2.40GHz * 4, 32GB DDR3 RAM, Intel(R) HD Graphics Family 2GB VRAM * 3, 1TB HD @ 5,400 RPM
  2. uncomment - THINKPADW530 [42763JZ], Microsoft Windows 10 Pro 1803 (10.0.17134.320), Intel Core i7-2760QM CPU @ 2.40GHz * 4, 32GB DDR3 RAM, Intel(R) HD Graphics Family 2GB VRAM * 3, 1TB HD @ 5,400 RPM
  3. Microsoft Windows 10 Pro 1803 (10.0.17134.191), Intel Core i7-4600U CPU @ 2.10GHz * 2, 8GB FBD2 RAM, Nvidia GeForce RTX 2080 Ti 8G SDRAM * 1, 128GB SSD
  4. Microsoft Windows 7 Ultimate  SP 1 (6.1.7601.24544), Intel Core i7 CPU 920 @ 2.67GHz * 4, 9GB RAM, GeForce GTX 750 Ti 2GB * 1, 1TB HD

No more cobbling this together, let's adopt a universal standard. 

Version 1 here

Version 2 Update:  
  1. Grabs  HD RPMs from P/Invoke ("kernel32.dll") from hard drive manufactures driver information. This gets the most accurate RPMs available, if supplied. No other script is doing this so far.
  2. Added memory type
  3. Adds GPU info, with proviso reports max GPU RAM size, type and description found for brevity
Download Version 2


  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
#============================================================================================================================================================
# AUTHOR:         metadataconsult@gmail.com
# WEBSITE:        http://metadataconsulting.blogspot.com
#
# SCRIPT NAME:    SimpleSysInfo-The1Linerv2.ps1  
# DATE:           11/02/2018 
# VERSION:        1.1.2.18275
#
# SYNPOSIS:       The 1 liner for essential PC/Sys info, using non-identifying specs for a post, quote or tweet 
# COMMENT:        No more cobling this together, universal standard. Detects SSD vs HD with rotary speed
#
# V2 IMPROVEMENTS:Gets hard drive rotations speed (RPMs) from kernel32.dll P/Invoke method, and better error transparency.
#                 Adds GPU, with proviso reports max GPU RAM size,type and description found for brevity
#                 Added RAM type
#                 
# EXECUTE:        .\SimpleSysInfo-The1Linerv2.ps1 (WITH ADMINISTRATOR PRIVLEDGES)
#
# RUN AS ADMIN :  Start-Process powershell -Verb runAs
#
# OUTPUT:         Microsoft Windows 10 Pro 1803 (10.0.17134.320), Intel Core i7-2760QM CPU @ 2.40GHz * 4, 32GB DDR3 RAM, Intel(R) HD Graphics Family 2GB VRAM * 3, 1TB HD @ 5,400 RPM
# OR uncomment    THINKPADW530 [42763JZ], Microsoft Windows 10 Pro 1803 (10.0.17134.320), Intel Core i7-2760QM CPU @ 2.40GHz * 4, 32GB DDR3 RAM, Intel(R) HD Graphics Family 2GB VRAM * 3, 1TB HD @ 5,400 RPM
# SSD SAMPLE:     Microsoft Windows 10 Pro 1803 (10.0.17134.191), Intel Core i7-4600U CPU @ 2.10GHz * 2, 8GB FBD2 RAM, Nvidia GeForce RTX 2080 Ti 8G SDRAM * 1, 128GB SSD
#
# LICENSE SUMMARY In a nutshell, you are not allowed to copyright, or take a patent on this code, or profit from it, those are or will be under perview of author. Otherwise, you are free to distribute and use.
# LICENSE URL:    http://metadataconsulting.blogspot.com/p/non-profit-open-software-license-3.html
#============================================================================================================================================================

#Requires -Version 3.0
$versionMinimum = [Version]'3.0'
if ($versionMinimum -gt $PSVersionTable.PSVersion)
{ 
    Write-Host "Requires PowerShell version 3.0"
    Write-Host "Running PowerShell $($PSVersionTable.PSVersion)"
    Break 
}

Function Get-SimpleSysInfo {
    Param ($List)

    #Build array collectn
    $infoCollection = @() 
       
    Foreach ($l in $list)
    {
     $BootInfo = Get-WmiObject Win32_BootConfiguration -ComputerName $l #Get Boot Information
        $CPUInfo = Get-WmiObject Win32_Processor -ComputerName $l #Get CPU Information
     $OSInfo = Get-WmiObject Win32_OperatingSystem -ComputerName $l #Get OS Information
        $PCInfo = Get-WmiObject Win32_ComputerSystem -ComputerName $l #Get PC Information
        $GPUInfo = Get-WmiObject Win32_VideoController -ComputerName $l #Get GPU
        $MemInfo = Get-WmiObject Win32_PhysicalMemory -ComputerName $l #Get Memory
    
        $BootDriveLetter =  $BootInfo.BootDirectory[0..1] -join ''
        $BootDiskNumber = $BootInfo.Caption.Split('\\')[2]
        $BootDiskNumber = $BootDiskNumber[($BootDiskNumber.Length-1)..$BootDiskNumber.Length] -join ''
        $BootPartitionNumber = $BootInfo.Caption.Split('\\')[3]
        $BootPartitionNumber = $BootPartitionNumber[($BootPartitionNumber.Length-1)..$BootPartitionNumber.Length] -join ''
   
        # Alternatives
        #        Get-WmiObject Win32_DiskDrive | sort Index | ft Index,DeviceID,@{l='Signature';e={"{0:X}" -f $_.Signature}},Model -a
        #
        #        $Disk = Get-WmiObject -Class Win32_logicaldisk | Where {$_.DeviceID -Match $BootDriveLetter}
        #        $DiskPartition = $Disk.GetRelated('Win32_DiskPartition')
        #        $DeviceID = $DiskPartition | Select-Object -Property DeviceID
        #        $Devicepart1 = ($DeviceID -split "Disk #")[1]; 
        #        $BootDiskNumber = ($Devicepart1 -split ",")[0]; 

        $OSServicePack = $OSInfo.ServicePackMajorVersion
        [version]$OSVersionType = $OSInfo | Select-Object -ExpandProperty Version
        
        #for Window 10+ release number, otherwise SP number [implicit computername scope, NO where clause]
        try
        {
            $OSVersion = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name ReleaseID -ErrorAction Stop).ReleaseID
        }
        catch
        {
            $OSVersion = $OSInfo.Version
        }
        #implicit computername scope, NO where clause       
        try
        {
            [string]$UpdateBuildRevision = $(Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name UBR -ErrorAction Stop).UBR
            $UpdateBuildRevision = "." + $UpdateBuildRevision 
        }
        catch
        {
            $UpdateBuildRevision = ""
        }
        $CurrentBuild = $OSInfo.Version + $UpdateBuildRevision 

        #CPU info
        $CPUManufacturer = $CPUInfo | Select-Object -ExpandProperty Name
        #Manufacturer retail name contains dup spaces, save space for 1 liner
        $CPUManufacturer = $CPUManufacturer -replace '\s+', ' '
        $CPUManufacturer =$CPUManufacturer -replace '\(R\)', '' 
        $CPUManufacturer =$CPUManufacturer -replace '\(TM\)', '' 
        
        $CPUNumberOfCores = $CPUInfo | Select-Object -ExpandProperty NumberOfCores

     #Get Memory Information. The data will be shown in a table as MB, rounded to the nearest second decimal.
     #$OSTotalVirtualMemory = [math]::round($OSInfo.TotalVirtualMemorySize / 1MB, 2)
     #$OSTotalVisibleMemory = [math]::round(($OSInfo.TotalVisibleMemorySize / 1MB), 2)
     #$IPAddress = Get-WmiObject win32_Networkadapterconfiguration -ComputerName $l | Where-Object {$_.ipaddress -notlike $null}
        
    
        $PhysicalMemoryPrint = $MemInfo | Measure-Object -Property capacity -Sum | % {Get-FriendlyRAMSize -Bytes $_.sum}
        $MemTypeDesc =  Get-RAMType $MemInfo[0].MemoryType 
                  
        if( $ExecutionContext.SessionState.LanguageMode -eq "ConstrainedLanguage"){ #powershell 3.0 or others 
          Write-Warning "Cannot add type/function embedded C# script which graps Drive Type and RPMs because your language mode is $($ExecutionContext.SessionState.LanguageMode)"  
          $RPMs = 4
        }
        else{
            [UInt32]$RPMs = GetHDRPMSSD $BootDriveLetter 
        }
        
        #Tue 02-Oct-18 3:50pm v2
        #SOURCE: http://www.t13.org/documents/UploadedDocuments/docs2009/d2015r1a-ATAATAPI_Command_Set_-_2_ACS-2.pdf
        #SECTION 7.18.7.81 
        #        Word 217: Nominal media rotation rate 
        #        Word 217 indicates the nominal media rotation rate of the device and is defined in table:
        #          Value           Description
        #          --------------------------------
        #          0000h           Rate not reported
        #          0001h           Non-rotating media (e.g., solid state device)
        #          0002h-0400h     Reserved
        #          0401h-FFFEh     Nominal media rotation rate in rotations per minute (rpm)
        #                          (e.g., 7 200 rpm = 1C20h)
        #          FFFFh           Reserved
                
        if ($RPMs -eq 0) {
           $HDTypeSpeedPrint = "HD" # the manufacturer has not encoded Rotation Rate/Spindle Speed - Check using https://gsmartcontrol.sourceforge.io
           Write-Warning "The disk drive manufacturer has not encoded Rotation Rate/Spindle Speed, therefore RPMs is not available."
        }
        elseif ($RPMs -eq 1) {
            $HDTypeSpeedPrint = "SSD"
        }
        elseif ($RPMs -eq 2) {
            $HDTypeSpeedPrint = "HD"
        }
        elseif ($RPMs -eq 3) {
            $HDTypeSpeedPrint = ""; 
            Write-Warning "Unknown error. Soln: Start-Process powershell -Verb runAs"
        }
        elseif ($RPMs -eq 4) {
            $HDTypeSpeedPrint = ""; 
            Write-Warning "Soln: Run in Powershell_ISE.exe as Admin"
        }
        elseif ($RPMs -eq 7) {
            $HDTypeSpeedPrint = ""; 
            Write-Warning "Embedded C# Script does not have elevated Admin privledges to grab Drive Type and RPM speed info. Soln: Start-Process powershell -Verb runAs"
        }
        elseif ($RPMs -eq 11) {
            $HDTypeSpeedPrint = ""; 
            Write-Warning "System cannot find that drive. $BootDriveLetter" 
        }
        elseif ($RPMs -gt 1024 -and $RPMs -lt 65535) {
            $HDTypeSpeedPrint = "HD @ " + "{0:N0} RPM" -f $RPMs
        } else {
            $HDTypeSpeedPrint = "HD"
        }

        $PhysicalDrive = "\\.\PHYSICALDRIVE"+$BootDiskNumber     

        $HDSizeOnDiskPrint = Get-WmiObject -Class Win32_LogicalDisk -ComputerName $l | Where-Object {$_.DriveType -ne 5 -and $_.Name -eq $BootDriveLetter} | Measure-Object -Property Size -Sum  | % {Get-FriendlyByteSize -Bytes $_.Sum}
        
        $HDSizeActualPrint = Get-WmiObject -Class Win32_DiskDrive -ComputerName $l | Where-Object {$_.DeviceID -eq $PhysicalDrive} | Measure-Object -Property Size -Sum  | % {Get-FriendlySize -Number $_.sum}
        
        #$HDSizeOnDisk = Get-WmiObject -Class Win32_LogicalDisk | Where-Object {$_.DriveType -ne 5 -and $_.Name -EQ $BootDriveLetter} | Measure-Object -Property Size -Sum  | % {"{0:N1}" -f ($_.sum/1GB) -as [float]}
        #$HDSizeActual = Get-WmiObject -Class Win32_DiskDrive | Where-Object {$_.DeviceID -eq $PhysicalDrive} | Measure-Object -Property Size -Sum  | % {"{0:N1}" -f ($_.sum/1000000000) -as [float]}
        #$HDDiffPercentage = ($HDSizeOnDisk - $HDSizeActual)/$HDSizeOnDisk * 100 # percentage lost space to marketing misundestanding

        #Thu 04-Oct-18 1:52pm v2 - add GPU
        #$MaxGPU = New-Object -TypeName PSObject
        $GPUCnt = ($GPUInfo).count
        If ([string]::IsNullOrEmpty($GPUCnt)) { $GPUCnt=1 } else {Write-Warning "More that one GPU Card detected. Reporting max GPU RAM size and description found for brevity."}

        $MaxGPUProcName = ""
        $MaxGPUTypeNo = 0
        $MaxGPUTypeDesc = ""
        $MaxRam = 0
       
        Foreach ($Card in $GPUInfo)
        {
            if ($MaxRam -lt $Card.AdapterRAM) 
            {
                $MaxRam = $Card.AdapterRAM
                $MaxGPUProcName = $Card.VideoProcessor
                $MaxGPUTypeNo = $Card.VideoMemoryType

                #$MaxGPU | Add-Member NoteProperty "$($Card.DeviceID)_VideoProcessor" $Card.VideoProcessor
                #$MaxGPU | Add-Member NoteProperty "$($Card.DeviceID)_Description" $Card.Description #Probably not needed. Seems to just echo the name. Left here in case I'm wrong!
                #$MaxGPU | Add-Member NoteProperty "$($Card.DeviceID)_Vendor" $Card.AdapterCompatibility
                #$MaxGPU | Add-Member NoteProperty "$($Card.DeviceID)_PNPDeviceID" $Card.PNPDeviceID
                #$MaxGPU | Add-Member NoteProperty "$($Card.DeviceID)_DriverVersion" $Card.DriverVersion
                   
                #$MaxGPU | Add-Member NoteProperty "$($Card.DeviceID)_AdapterRam" $getRAM   #$Card.AdapterRAM
            }
        }
        $MaxRam = Get-FriendlyRAMSize $MaxRam
        $MaxGPUTypeDesc = Get-GPURAMType $MaxGPUTypeNo

        #Hold output rows
  $infoObject = New-Object PSObject
  
        #Craft formatted row
        Add-Member -inputObject $infoObject -memberType NoteProperty -name "Computer Name" -value $l
        Add-Member -inputObject $infoObject -memberType NoteProperty -name "PC Manufacturer Name" -value $PCInfo.Name
        Add-Member -inputObject $infoObject -memberType NoteProperty -name "PC Manufacturer Model" -value $PCInfo.Model      
        Add-Member -inputObject $infoObject -memberType NoteProperty -name "OS Name" -value $OSInfo.Caption


        If ($OSVersionType.Major -lt 10) {
            Add-Member -inputObject $infoObject -memberType NoteProperty -name "Service Pack" -value $OSServicePack
        } else {           
            Add-Member -inputObject $infoObject -memberType NoteProperty -name "OS Version" -value $OSVersion
        }

  Add-Member -inputObject $infoObject -memberType NoteProperty -name "OS Build" -value $CurrentBuild
 
  #Add-Member -inputObject $infoObject -memberType NoteProperty -name "Server Name" -value $CPU.SystemName # alternative
        #Add-Member -inputObject $infoObject -memberType NoteProperty -name "IPv4_Address" -value $IPAddress.IPaddress[0]

        Add-Member -inputObject $infoObject -memberType NoteProperty -name "CPU Manufacturer" -value $CPUManufacturer
  #Add-Member -inputObject $infoObject -memberType NoteProperty -name "Model" -value $CPU.Description
  #Add-Member -inputObject $infoObject -memberType NoteProperty -name "Manufacturer" -value $CPU.Manufacturer

  Add-Member -inputObject $infoObject -memberType NoteProperty -name "Physical Cores" -value $CPUNumberOfCores
  #Add-Member -inputObject $infoObject -memberType NoteProperty -name "CPU L2 Cache Size" -value $CPU.L2CacheSize
  #Add-Member -inputObject $infoObject -memberType NoteProperty -name "CPU L3 Cache Size" -value $CPU.L3CacheSize
  #Add-Member -inputObject $infoObject -memberType NoteProperty -name "Sockets" -value $CPU.SocketDesignation
  #Add-Member -inputObject $infoObject -memberType NoteProperty -name "Logical Cores" -value $CPU.NumberOfLogicalProcessors


        Add-Member -inputObject $infoObject -memberType NoteProperty -name "RAM" -value $PhysicalMemoryPrint 
        Add-Member -inputObject $infoObject -memberType NoteProperty -name "RAM Type" -value $MemTypeDesc 

  #Add-Member -inputObject $infoObject -memberType NoteProperty -name "RAM (GB)" -value $PhysicalMemory
  #Add-Member -inputObject $infoObject -memberType NoteProperty -name "Total Virtual Memory (MB)" -value $OSTotalVirtualMemory
  #Add-Member -inputObject $infoObject -memberType NoteProperty -name "Total Visable Memory (MB)" -value $OSTotalVisibleMemory
        
        Add-Member -inputObject $infoObject -memberType NoteProperty -name "GPU Manufacturer" -value $MaxGPUProcName 
        Add-Member -inputObject $infoObject -memberType NoteProperty -name "GPU RAM" -value $MaxRam
        Add-Member -inputObject $infoObject -memberType NoteProperty -name "GPU Type" -value $MaxGPUTypeDesc
        Add-Member -inputObject $infoObject -memberType NoteProperty -name "GPU Cores" -value $GPUCnt
        
        Add-Member -inputObject $infoObject -memberType NoteProperty -name "OS Drive - Retail Size" -value $HDSizeActualPrint
        Add-Member -inputObject $infoObject -memberType NoteProperty -name "OS Drive - Size On Disk" -value $HDSizeOnDiskPrint
        #Add-Member -inputObject $infoObject -memberType NoteProperty -name "Hard Drive C: Retail Size  (GB)" -value $HDSizeActual
        #Add-Member -inputObject $infoObject -memberType NoteProperty -name "Hard Drive C: Size On Disk (GB)" -value $HDSizeOnDisk
        #Add-Member -inputObject $infoObject -memberType NoteProperty -name "Hard Drive C: Marketing Loss %" -value $HDDiffPercentage

     Add-Member -inputObject $infoObject -memberType NoteProperty -name "OS Drive - Type" -value $HDTypeSpeedPrint
    
  $infoCollection += $infoObject 
    }
    #Output to the screen for a visual feedback or CSV
    $infoCollection 
    #| Export-Csv -path .\SimpleSysInfo_$((Get-Date).ToString('MMddyyyy_hhmmss')).csv -NoTypeInformation #Export the results in csv file.


    #the quotable one liner    
    foreach ($ic in $infoCollection) {
 
        If ($OSVersionType.Major -lt 10) {
             #$ic.'PC Manufacturer Name'+" ["+$ic.'PC Manufacturer Model' +"], "+ $ic.'OS Name'  + " SP " +$ic.'Service Pack' + " (" +$ic.'OS Build' + "), " + ($ic.'CPU Manufacturer')  + " * " + $ic.'Physical Cores' + ", " + $ic.RAM + " RAM, " + $ic.'OS Drive - Retail Size' + " " + $ic.'OS Drive - Type'
             $ic.'OS Name'  + " SP " +$ic.'Service Pack' + " (" +$ic.'OS Build' + "), " + ($ic.'CPU Manufacturer')  + " * " + $ic.'Physical Cores' + ", " + $ic.RAM + " " + $ic.'RAM Type' + ", " + $ic.'GPU Manufacturer' + " " +$ic.'GPU RAM' + $ic.'GPU Type' + " * " + $ic.'GPU Cores' + ", " + $ic.'OS Drive - Retail Size' + " " + $ic.'OS Drive - Type'
        } else {           
             #$ic.'PC Manufacturer Name'+" ["+$ic.'PC Manufacturer Model' +"], "+ $ic.'OS Name'  + " " + $ic.'OS Version' + " (" +$ic.'OS Build' + "), " + ($ic.'CPU Manufacturer') + " * " + $ic.'Physical Cores' + ", " + $ic.RAM + " RAM, " + $ic.'OS Drive - Retail Size' + " " + $ic.'OS Drive - Type'
             $ic.'OS Name'  + " " + $ic.'OS Version' + " (" +$ic.'OS Build' + "), " + ($ic.'CPU Manufacturer') + " * " + $ic.'Physical Cores' + ", " + $ic.RAM +" "+ $ic.'RAM Type' + ", " + ($ic.'GPU Manufacturer') + " " +$ic.'GPU RAM' + $ic.'GPU Type' + " * " + $ic.'GPU Cores' + ", " + $ic.'OS Drive - Retail Size' + " " + $ic.'OS Drive - Type'
        }

    }

} #End Get-SimpleSysInfo

# The problem with forcing a double into an integer in modulo operations is that Powershell uses banker's rounding algorithm. Hence make our own fn
function Get-FriendlyByteSize {
    param($Bytes)
    $sizes='Bytes,KB,MB,GB,TB,PB,EB,ZB' -split ','
    for($i=0; ($Bytes -ge 1kb) -and 
        ($i -lt $sizes.Count); $i++) {$Bytes/=1kb}
    $N=2; if($i -eq 0) {$N=0}
    "{0:N$($N)} {1}" -f $Bytes, $sizes[$i]
}

function Get-FriendlyRAMSize {
    param($Bytes)
    $sizes='Bytes,KB,MB,GB,TB,PB,EB,ZB' -split ','
    for($i=0; ($Bytes -ge 1kb) -and 
        ($i -lt $sizes.Count); $i++) {$Bytes/=1kb}
    $N=0; if($i -eq 0) {$N=0}
    "{0:N$($N)}{1}" -f $Bytes, $sizes[$i]
}

function Get-FriendlySize {
    param($Number)
    $sizes='Bytes,KB,MB,GB,TB,PB,EB,ZB' -split ','
    for($i=0; ($Number -ge 1000) -and ($i -lt $sizes.Count); $i++)
    {$Number/=1000}
    $N=0; if($i -eq 0) {$N=0}
    "{0:N$($N)}{1}" -f $Number, $sizes[$i]
}

Function Get-RAMType {
    Param ($type)
    switch ( $type )
    {
        0 { $memType = "RAM" } #other
        1 { $memType = "RAM" } #unknown
        2 { $memType = "DRAM" }
        3 { $memType = "Synchronous DRAM" }
        4 { $memType = "Cache DRAM" }
        5 { $memType = "EDO RAM" }
        6 { $memType = "EDRAM" }
        7 { $memType = "VRAM" }
        8 { $memType = "SRAM" }
        9 { $memType = "RAM" }
        10 { $memType = "ROM" }
        11 { $memType = "Flash ROM" }
        12 { $memType = "EEPROM" }
        13 { $memType = "FEPROM" }
        14 { $memType = "EPROM" }
        15 { $memType = "CDRAM" }
        16 { $memType = "3DRAM" }
        17 { $memType = "SDRAM" }
        18 { $memType = "SGRAM" }
        19 { $memType = "RDRAM" }
        20 { $memType = "DDR RAM" }
        21 { $memType = "DDR2 RAM" }
        22 { $memType = "DDR2 FB-DIMM RAM" }
        23 { $memType = "RAM" } #unknown
        24 { $memType = "DDR3 RAM" }
        25 { $memType = "FBD2 RAM" }
    }
    return [string]$memType
}

Function Get-GPURAMType {
    Param ($type)
    switch ( $type )
    {
        1 {$vidmemType=""} #other
        2 {$vidmemType=""} #unknown commonly used by grahpics device companies
        3 {$vidmemType=" VRAM"}
        4 {$vidmemType=" DRAM"}
        5 {$vidmemType=" SRAM"}
        6 {$vidmemType=" WRAM"}
        7 {$vidmemType=" EDO RAM"}
        8 {$vidmemType=" Burst Synchronous DRAM"}
        9 {$vidmemType=" Pipelined Burst SRAM"}
        10 {$vidmemType=" CDRAM"}
        11 {$vidmemType=" 3DRAM"}
        12 {$vidmemType=" SDRAM"}
        13 {$vidmemType=" SGRAM"}
     }
    return [string]$vidmemType
}

<#
.SYNOPSIS
   Detects if the passed drive letter is a Solid State Disk (SSD) or a
   spindle disk. Returns integer for RPM speed or 1 for SSD.

.DESCRIPTION
   
   The methods used for detecting are by reading the Nominal Media Rotation
   Rate. These values are measured through method calls
   into the Kernel32.dll. If either of the Win32 DLL calls return true then
   the script will return false. If an exception occurs in either of the
   Win32 DLL calls, the return value will be dependant on the remaining call.

.PARAMETER BootDiskLetter
#>

Function GetHDRPMSSD {
[CmdletBinding(SupportsShouldProcess=$true,
               ConfirmImpact="Low")]
[OutputType([UInt32])]
Param
(
    [Parameter(Mandatory=$true,
               ValueFromPipeline=$true,
               ValueFromPipelineByPropertyName=$true,
               Position=0)]
    [String]
    $BootDriveLetterwithcolon
)

Begin {
    $code = @"
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;
using System.Text;
 
namespace Util
{
    public class GetHDRPMSSD
    {
        // For CreateFile to get handle to drive
        private const uint GENERIC_READ = 0x80000000;
        private const uint GENERIC_WRITE = 0x40000000;
        private const uint FILE_SHARE_READ = 0x00000001;
        private const uint FILE_SHARE_WRITE = 0x00000002;
        private const uint OPEN_EXISTING = 3;
        private const uint FILE_ATTRIBUTE_NORMAL = 0x00000080;
 
        // CreateFile to get handle to drive
        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern SafeFileHandle CreateFileW(
            [MarshalAs(UnmanagedType.LPWStr)]
            string lpFileName,
            uint dwDesiredAccess,
            uint dwShareMode,
            IntPtr lpSecurityAttributes,
            uint dwCreationDisposition,
            uint dwFlagsAndAttributes,
            IntPtr hTemplateFile);
 
        // For control codes
        private const uint FILE_DEVICE_MASS_STORAGE = 0x0000002d;
        private const uint IOCTL_STORAGE_BASE = FILE_DEVICE_MASS_STORAGE;
        private const uint FILE_DEVICE_CONTROLLER = 0x00000004;
        private const uint IOCTL_SCSI_BASE = FILE_DEVICE_CONTROLLER;
        private const uint METHOD_BUFFERED = 0;
        private const uint FILE_ANY_ACCESS = 0;
        private const uint FILE_READ_ACCESS = 0x00000001;
        private const uint FILE_WRITE_ACCESS = 0x00000002;
 
        private static uint CTL_CODE(uint DeviceType, uint Function,
                                     uint Method, uint Access)
        {
            return ((DeviceType << 16) | (Access << 14) |
                    (Function << 2) | Method);
        }
 
        // For DeviceIoControl to check no seek penalty
        private const uint StorageDeviceSeekPenaltyProperty = 7;
        private const uint PropertyStandardQuery = 0;
 
        [StructLayout(LayoutKind.Sequential)]
        private struct STORAGE_PROPERTY_QUERY
        {
            public uint PropertyId;
            public uint QueryType;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
            public byte[] AdditionalParameters;
        }
 
        [StructLayout(LayoutKind.Sequential)]
        private struct DEVICE_SEEK_PENALTY_DESCRIPTOR
        {
            public uint Version;
            public uint Size;
            [MarshalAs(UnmanagedType.U1)]
            public bool IncursSeekPenalty;
        }
 
        // DeviceIoControl to check no seek penalty
        [DllImport("kernel32.dll", EntryPoint = "DeviceIoControl",
                   SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool DeviceIoControl(
            SafeFileHandle hDevice,
            uint dwIoControlCode,
            ref STORAGE_PROPERTY_QUERY lpInBuffer,
            uint nInBufferSize,
            ref DEVICE_SEEK_PENALTY_DESCRIPTOR lpOutBuffer,
            uint nOutBufferSize,
            out uint lpBytesReturned,
            IntPtr lpOverlapped);
 
        // For DeviceIoControl to check nominal media rotation rate
        private const uint ATA_FLAGS_DATA_IN = 0x02;
 
        [StructLayout(LayoutKind.Sequential)]
        private struct ATA_PASS_THROUGH_EX
        {
            public ushort Length;
            public ushort AtaFlags;
            public byte PathId;
            public byte TargetId;
            public byte Lun;
            public byte ReservedAsUchar;
            public uint DataTransferLength;
            public uint TimeOutValue;
            public uint ReservedAsUlong;
            public IntPtr DataBufferOffset;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
            public byte[] PreviousTaskFile;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
            public byte[] CurrentTaskFile;
        }
 
        [StructLayout(LayoutKind.Sequential)]
        private struct ATAIdentifyDeviceQuery
        {
            public ATA_PASS_THROUGH_EX header;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
            public ushort[] data;
        }
 
        // DeviceIoControl to check nominal media rotation rate
        [DllImport("kernel32.dll", EntryPoint = "DeviceIoControl",
                   SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool DeviceIoControl(
            SafeFileHandle hDevice,
            uint dwIoControlCode,
            ref ATAIdentifyDeviceQuery lpInBuffer,
            uint nInBufferSize,
            ref ATAIdentifyDeviceQuery lpOutBuffer,
            uint nOutBufferSize,
            out uint lpBytesReturned,
            IntPtr lpOverlapped);
 
        // For error message
        private const uint FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
 
        [DllImport("kernel32.dll", SetLastError = true)]
        static extern uint FormatMessage(
            uint dwFlags,
            IntPtr lpSource,
            uint dwMessageId,
            uint dwLanguageId,
            StringBuilder lpBuffer,
            uint nSize,
            IntPtr Arguments);
 

        // Method for no seek penalty, alternate to determine if this spindle disk aka hard drive
        // Method for no seek penalty
        public static bool HasSeekPenalty(string sDrive)
        {
            SafeFileHandle hDrive = CreateFileW(
                sDrive,
                0, // No access to drive
                FILE_SHARE_READ | FILE_SHARE_WRITE,
                IntPtr.Zero,
                OPEN_EXISTING,
                FILE_ATTRIBUTE_NORMAL,
                IntPtr.Zero);

            if (hDrive == null || hDrive.IsInvalid)
            {
                string message = GetErrorMessage(Marshal.GetLastWin32Error());
                throw new System.Exception(message);
            }

            uint IOCTL_STORAGE_QUERY_PROPERTY = CTL_CODE(
                IOCTL_STORAGE_BASE, 0x500,
                METHOD_BUFFERED, FILE_ANY_ACCESS); // From winioctl.h
 
            STORAGE_PROPERTY_QUERY query_seek_penalty =
                new STORAGE_PROPERTY_QUERY();
            query_seek_penalty.PropertyId = StorageDeviceSeekPenaltyProperty;
            query_seek_penalty.QueryType = PropertyStandardQuery;
 
            DEVICE_SEEK_PENALTY_DESCRIPTOR query_seek_penalty_desc =
                new DEVICE_SEEK_PENALTY_DESCRIPTOR();
 
            uint returned_query_seek_penalty_size;
 
            bool query_seek_penalty_result = DeviceIoControl(
                hDrive,
                IOCTL_STORAGE_QUERY_PROPERTY,
                ref query_seek_penalty,
                (uint)Marshal.SizeOf(query_seek_penalty),
                ref query_seek_penalty_desc,
                (uint)Marshal.SizeOf(query_seek_penalty_desc),
                out returned_query_seek_penalty_size,
                IntPtr.Zero);
 
            hDrive.Close();
 
            if (query_seek_penalty_result == false)
            {
                string message = GetErrorMessage(Marshal.GetLastWin32Error());
                throw new System.Exception(message);
            }
            else
            {
                return query_seek_penalty_desc.IncursSeekPenalty;
            }
        }

        // Method for nominal media rotation rate
        // (Administrative privilege is required)
        public static UInt32 HasNominalMediaRotationRate(string sDrive)
        {
            SafeFileHandle hDrive = CreateFileW(
                sDrive,
                GENERIC_READ | GENERIC_WRITE, // Administrative privilege is required
                FILE_SHARE_READ | FILE_SHARE_WRITE,
                IntPtr.Zero,
                OPEN_EXISTING,
                FILE_ATTRIBUTE_NORMAL,
                IntPtr.Zero);
 
            if (hDrive == null || hDrive.IsInvalid)
            {
                string message = GetErrorMessage(Marshal.GetLastWin32Error());
                throw new System.Exception(message); //embedded in powershell this does nothing
            }
 
            uint IOCTL_ATA_PASS_THROUGH = CTL_CODE(
                IOCTL_SCSI_BASE, 0x040b, METHOD_BUFFERED,
                FILE_READ_ACCESS | FILE_WRITE_ACCESS); // From ntddscsi.h
 
            ATAIdentifyDeviceQuery id_query = new ATAIdentifyDeviceQuery();
            id_query.data = new ushort[256];
 
            id_query.header.Length = (ushort)Marshal.SizeOf(id_query.header);
            id_query.header.AtaFlags = (ushort)ATA_FLAGS_DATA_IN;
            id_query.header.DataTransferLength =
                (uint)(id_query.data.Length * 2); // Size of "data" in bytes
            id_query.header.TimeOutValue = 3; // Sec
            id_query.header.DataBufferOffset = (IntPtr)Marshal.OffsetOf(
                typeof(ATAIdentifyDeviceQuery), "data");
            id_query.header.PreviousTaskFile = new byte[8];
            id_query.header.CurrentTaskFile = new byte[8];
            id_query.header.CurrentTaskFile[6] = 0xec; // ATA IDENTIFY DEVICE
 
            uint retval_size;
 
            bool result = DeviceIoControl(
                hDrive,
                IOCTL_ATA_PASS_THROUGH,
                ref id_query,
                (uint)Marshal.SizeOf(id_query),
                ref id_query,
                (uint)Marshal.SizeOf(id_query),
                out retval_size,
                IntPtr.Zero);
 
            hDrive.Close();
 
            if (result == false)
            {
                string message = GetErrorMessage(Marshal.GetLastWin32Error());
                throw new System.Exception(message);
            }
            else
            {
                // Word index of nominal media rotation rate
                const int kNominalMediaRotRateWordIndex = 217;
 
                //Tue 02-Oct-18 2:33pm v2 - updated 
                //Index of nominal media rotation rate
                //SOURCE: http://www.t13.org/documents/UploadedDocuments/docs2009/d2015r1a-ATAATAPI_Command_Set_-_2_ACS-2.pdf
                //          7.18.7.81 Word 217
                //QUOTE: Word 217 indicates the nominal media rotation rate of the device and is defined in table:
                //          Value           Description
                //          --------------------------------
                //          0000h           Rate not reported
                //          0001h           Non-rotating media (e.g., solid state device)
                //          0002h-0400h     Reserved
                //          0401h-FFFEh     Nominal media rotation rate in rotations per minute (rpm)
                //                          (e.g., 7200 rpm = 1C20h)
                //          FFFFh           Reserved
                
                //http://qaru.site/questions/493997/detecting-ssd-in-windows
                //#define kNominalMediaRotRateWordIndex 217
                //_tprintf(L"%d", (UINT)id_query.data[kNominalMediaRotRateWordIndex]);

                return id_query.data[kNominalMediaRotRateWordIndex];//no hex translation needed

            }
        }
 
        // Method for error message
        private static string GetErrorMessage(int code)
        {
            StringBuilder message = new StringBuilder(255);
 
            FormatMessage(
              FORMAT_MESSAGE_FROM_SYSTEM,
              IntPtr.Zero,
              (uint)code,
              0,
              message,
              (uint)message.Capacity,
              IntPtr.Zero);
 
            return message.ToString();
        }
    }
}
"@
    Add-Type -TypeDefinition $code -PassThru | Out-Null

    $hasRotationRate = 0
    $hasSeekPenalty = $false
}

Process {
    
    [UInt32]$hasRotationRate = 0
    
    #v2 https://msdn.microsoft.com/en-us/1d35c087-6672-4fc6-baa1-a886dd9d3878?f=255&MSPPError=-2147217396
    $driveString = "\\.\"+$BootDriveLetterwithcolon; #v2 simpler 
    
    #v1 $driveString = "\\.\PhysicalDrive" + $PhysicalDiskId  #Wed 03-Oct-18 9:03am v1, org but why
    #v1 Write-Verbose -Message "Current disk item id is: $PhysicalDiskId"
 
    Write-Verbose -Message "Current disk string is: $driveString"
    Write-Verbose -Message "Calling Win32 DLL Method 'DeviceIoControl' in 'HasNominalMediaRotationRate'."
    if ($PSCmdlet.ShouldProcess("Physical Disk $PhysicalDiskId","Read Nominal Media Rotation Rate Property")) {
        try {
            $hasRotationRate = [Util.GetHDRPMSSD]::HasNominalMediaRotationRate([string]$driveString)
        } catch {
            
            Write-Verbose -Message "HasNominalMediaRotationRate detection failed with the following error;"
            Write-Verbose -Message $Error[0].Exception.Message
            
            if ($Error[0].Exception.Message -match 'Access is denied') 
            {
                $hasRotationRate = 007 #throw our own error spy message, meaning this is not being run in elevated Admin privledges
            }
            elseif ($Error[0].Exception.Message -match 'The system cannot find the file specified') 
            {
                $hasRotationRate = 11 #Wrong drive letter 
            }           
            else { 
                $hasRotationRate = 3 #Unknown error
                Write-Warning "HasNominalMediaRotationRate detection failed with the following error;"
                Write-Warning $Error[0].Exception.Message
            }
        }
    }
   
    Write-Verbose -Message "Calling Win32 DLL Method 'DeviceIoControl' in 'HasSeekPenalty'."
    if ($PSCmdlet.ShouldProcess("Physical Disk $PhysicalDiskId","Read Seek Penalty Property")) {
        try {
            $hasSeekPenalty = [Util.DetectSSD]::HasSeekPenalty([string]$driveString)
        } catch {
            Write-Verbose -Message "HasSeekPenalty detection failed with the following error;"
            Write-Verbose -Message $Error[0].Exception.Message
            $hasSeekPenalty = $false
        }
    }

    if ($hasRotationRate -eq 3 -and $hasSeekPenalty -eq $true) {
        $hasRotationRate = 2; # It's a hard drive
    }
    
    Write-Output -InputObject ($hasRotationRate)
    
}

End {
}
}

#Get your computer name, or a list of computers (comma seperated)
$PCList = $env:computername;

Get-SimpleSysInfo -List $PCList