Wednesday, July 25, 2018

Simple System Info - The One Liner - Powershell

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

Oct 4, 2018 Update Version 2 adds GPU info and more...

Example outputs; 

  1. Microsoft Windows 10 Pro 1803 (10.0.17134.81), Intel Core i7-2760QM CPU @ 2.40GHz * 4, 32GB RAM, 1TB HD @ 7,158 RPM
  2. THINKPADW530 [42763JZ], Microsoft Windows 10 Pro 1803 (10.0.17134.81), Intel Core i7-2760QM CPU @ 2.40GHz * 4, 32GB RAM, 1TB HD @ 7,158 RPM
  3. Microsoft Windows 10 Pro 1803 (10.0.17134.191), Intel Core i7-4600U CPU @ 2.10GHz * 2, 8GB RAM, 128GB SSD

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

Bonus: Detects SSD size and HD RPMs.


  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
#============================================================================================================================================================
# AUTHOR:         metadataconsult@gmail.com
# WEBSITE:        http://metadataconsulting.blogspot.com
#
# SCRIPT NAME:    SimpleSysInfo-The1Liner.ps1  
# DATE:           06/11/2018 
# VERSION:        1.1.1.18162
#
# 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
#                 
# EXECUTE:        .\SimpleSysInfo-The1Liner.ps1
#
# OUTPUT:         Microsoft Windows 10 Pro 1803 (10.0.17134.81), Intel Core i7-2760QM CPU @ 2.40GHz * 4, 32GB RAM, 1TB HD @ 7,158 RPM
# OR              THINKPADW530 [42763JZ], Microsoft Windows 10 Pro 1803 (10.0.17134.81), Intel Core i7-2760QM CPU @ 2.40GHz * 4, 32GB RAM, 1TB HD @ 7,158 RPM
# SSD SAMPLE:     Microsoft Windows 10 Pro 1803 (10.0.17134.191), Intel Core i7-4600U CPU @ 2.10GHz * 2, 8GB RAM, 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
    
        $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 ''

        $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 = Get-WmiObject CIM_PhysicalMemory -ComputerName $l | Measure-Object -Property capacity -Sum | % {Get-FriendlyRAMSize -Bytes $_.sum}
        
        $PhysicalDrive = "\\.\PHYSICALDRIVE"+$BootDiskNumber 
        $BootDiskModel = Get-WmiObject -Class Win32_DiskDrive -ComputerName $l | Where-Object {$_.DeviceID -eq $PhysicalDrive} | Select -ExpandProperty Model   
                
        # DOUBLE CHECK THIS -> https://msdn.microsoft.com/en-us/library/windows/desktop/hh830532(v=vs.85).aspx 
        # MSDN doc says RPM but cannot be, ASSUMING RPMilliseconds
        # Assuming RPMilliseconds not RPM in calculation  = 1 minute = 60 seconds = 60 × 1000 milliseconds = 60,000 ms.
        try{            
        
            [long]$SpindleSpeed = Get-WmiObject -Namespace "root\Microsoft\Windows\Storage" -Class "MSFT_PhysicalDisk" -ComputerName $l -ErrorAction Stop | Where-Object {$_.Model -eq $BootDiskModel} | Select -ExpandProperty SpindleSpeed

            # FOR SSD this will be 0
            if (![string]::IsNullOrEmpty($SpindleSpeed) -and $SpindleSpeed -ne 0)
            {
                $SpindleSpeed = [Math]::Round(($SpindleSpeed / 600000))
                $HDSpeedPrint = "{0:N0} RPM" -f $SpindleSpeed   
            } else {
                $HDSpeedPrint = ""
            }

        }
        catch
        {
            $HDSpeedPrint = ""
        }
  
        # Is windows OS drive SSD? PSVersion 3.0 
        $IsBootDiskSSD = Test-SSD $BootDiskNumber
        
        # finally get HD Type 
        if ($IsBootDiskSSD) {
            $HDTypeSpeedPrint = "SSD"
        } elseif (![string]::IsNullOrEmpty($HDSpeedPrint) -and $HDSpeedPrint -ne "0 RPM") {
            $HDTypeSpeedPrint = "HD @ " + $HDSpeedPrint
        } else {
            $HDTypeSpeedPrint = "HD"
        }

        $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

        #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 (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 "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 + " RAM, " + $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 + " RAM, " + $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]
}

<#
.SYNOPSIS
   Detects if the passed Physical Disk Id is a Solid State Disk (SSD) or a
   spindle disk. Returns true for an SSD and false for anything else.

.DESCRIPTION
   Use Get-PhysicalDisk to get the Physical Disk Ids for the system you wish
   to test. This script supports values being passed throught the pipeline.
   
   The methods used for detecting are by reading the Nominal Media Rotation
   Rate and Seek Penalty. 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 PhysicalDiskId
    The LUN based physical disk id.

.EXAMPLE
   Get-PhysicalDisk | Select-Object -ExpandProperty DeviceId | Test-SSD

   This example will test all the disks on the local computer.

.EXAMPLE
   if (Test-SSD -PhysicalDiskId 0) { $delay = 0 }

   This example will change the delay variable on a script if the
   first physical disk is an SSD.
#>

Function Test-SSD {
[CmdletBinding(SupportsShouldProcess=$true,
               ConfirmImpact="Low")]
[OutputType([boolean])]
Param
(
    [Parameter(Mandatory=$true,
               ValueFromPipeline=$true,
               ValueFromPipelineByPropertyName=$true,
               Position=0)]
    [Int]
    $PhysicalDiskId
)

Begin {
    $code = @"
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;
using System.Text;
 
namespace Util
{
    public class DetectSSD
    {
        // 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
        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 bool 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);
            }
 
            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
                // (1 means non-rotate device)
                const int kNominalMediaRotRateWordIndex = 217;
 
                if (id_query.data[kNominalMediaRotRateWordIndex] == 1)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }
 
        // 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

    $hasRotationRate = $true
    $hasSeekPenalty = $true
}

Process {

    $driveString = "\\.\PhysicalDrive" + $PhysicalDiskId
    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.DetectSSD]::HasNominalMediaRotationRate([string]$driveString)
        } catch {
            Write-Verbose -Message "HasNominalMediaRotationRate detection failed with the following error;"
            Write-Verbose -Message $Error[0].Exception.Message
            $hasRotationRate = $true
        }
    }

    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 = $true
        }
    }

    # Only return true if the disk has no rotation rate or no seek penalty.
    Write-Output -InputObject (!$hasRotationRate -or !$hasSeekPenalty)

}

End {
}
}

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

Get-SimpleSysInfo -List $PCList

Friday, July 20, 2018

How to use Microsoft OneDrive 2018 as Content Delivery Network (CDN)

For web developers who are mindful of Page Speed scores, finding a free Content Delivery Network (CDN) to load your static content from a cookie-free domain is always nice to have!!!

This is an examination of using Micorosoft OneDrive as a possible CDN for 2018. I will test this using https://onedrive.live.com to hosting an image 
MobiusColorGoodFinalRefined.png  (514 kBs), that is used as background image on an external site and can be lazy loaded.

Here's how to get the embed link for a resource on OneDrive. 

OneDrive URL for Image File

ImportantFor images only, this embed link is a direct download link and is not redirected. 









This will open the right-pane, where you can "Copy the URL to embed image" 




The embed URL for images only works as direct download link. This link does not set a cookie or require authentication parameters when requesting this link. Furthermore, it is not redirected, which theoretically should speed up the request.

Here's the link https://nfpjyq.sn.files.1drv.com/y4mdDSDVfWaN9o1W3c2uKqn3_74fyNXNzWRohoRAagyFk8m-WRN-f3oHMS93u5JVVvyyikcB8H7hftg5ZUx35li_fA1R9vIwddOw-zLLu3kD0Y0k8-v9oJD0uULz4KW1Fj8FTKmLampi9up0qeJR98sJjfwBbAlRDQR-3074iMAzREfxwahKpArcL7Yqyf32P9QsavulPuAjo28VzFh1xeHAA?width=1024&height=493&cropmode=none

The link request in Chrome timings window;


The total request time was unimpressive .9 secs. This disqualifies this techniques as a possible CDN, IMHO. 

OneDrive URL for All Other Resources

But for all other files this direct download link is not available. For example,  let's look at a common website Javascript file "scroll.js".

If you request an Embed URL you'll get an URL starting with https://onedrive.live.com/embed? and contains parameters authkey and resid. 

<iframe src="https://onedrive.live.com/embed?cid=5C91C14607824FC4&resid=5C91C14607824FC4%211671&authkey=AINpYbSMwQFVSu8" width="98" height="120" frameborder="0" scrolling="no"></iframe>























This URL does not work directly in the browser, you get an "This item won't load right now." error.

https://onedrive.live.com/embed?cid=5C91C14607824FC4&resid=5C91C14607824FC4%211671&authkey=AINpYbSMwQFVSu8

you can covert this link into to get direct download link, as follows;

https://onedrive.live.com/download?cid=5C91C14607824FC4&resid=5C91C14607824FC4%211671&authkey=AINpYbSMwQFVSu8

This link can embed in a website as a resource. But there's a caveat, this request sets a cookie and the URL is redirected.

How fast is this OneDrive as a CDN service for resources (other than images)?

Now let's examine in detail some network timings from FireFox Inspect window.


Here we see the download?cid link return a 302, and bounce back with the fulfilled  resolved 200 request for MobiusColorGoodFinalRefined.png. 

The total request time was 1.732s! 

Now lets examine some network timings from IE Inspect window.











Here we see the download?cid link return a 302, and bounce back with the fulfilled  resolved 200 request for MobiusColorGoodFinalRefined.png. 

The total request time was 1.148s! 

Now lets examine some network timings from Google Chrome Inspect window.

Interesting Google Chrome resolved this in one step for a super efficient total request time was .6 seconds! 


Conclusion

In the end, OneDrive is not an effective free Content Delivery Network (CDN) to load your static content, because resources take ~1 second of load time for most browsers. 

However, if you filter for Chrome in your JS code, it might suffice. 



Wednesday, July 18, 2018

Clearing Windows Defender Actions Recommended icon, is Onedrive being used?

Having a problem clear Windows Defender Actions Recommended (alert) icon ? 

One issue that arised and was annoying to track down that caused the Windows Defender Actions Recommended (alert) icon to remain is a hidden criterion set under "Virus and Threat Protection". 

Annoying because it was under Windows Defender Antivirus Options (a little hard to see in the dark theme) and Periodic Scanning was not enabled (but the option to be clear needs this to be enabled!)

And that is the RansomWare Protection rule, will be invalid if you are not connected to Onedrive. 

The a special rule has to be manually add an exception too.

Solution: 
  1. Goto "Virus and threat protection" -> "Windows Defender Advanced options" -> Set "Periodic scanning" to ON!



  2. Close and restart the window
  3. Goto "Virus and threat protection" -> "Windows Defender Advanced options" -> Scroll to "Ransomware protection" click to ignore in future. Maker sure the rest of the rules are a pass in this section.


Friday, July 13, 2018

C# TrimStart and TrimEnd with integer length parameter string extensions







This C# code overloads TrimStart and TrimEnd methods, adding an integer length parameter which  provides a more intuitive method call.
 
string numbers = "12345";
numbers.TrimStart(1);  //--> "2345" 
numbers.TrimEnd(1);    //--> "1234"
numbers.TrimStart(50); //--> "12345" 
numbers.TrimEnd(50);   //--> "12345"
//OR EASILY ENOUGH
numbers.TrimStart(50); //--> "" 
numbers.TrimEnd(50);   //--> ""
numbers.Truncate(50); //->""

In my implementation of TrimStart and TrimEnd methods, 'trim' implies a conditional removal. On overflow, we return entire string. Or easily enough depending on your needs return string.empty.

This is unlike the, Truncate extension method, which will truncate off the top or the end of the string and in overflow it will return null. See live code below.


Below is the code to add TrimStart(int length) and TrimEnd(int length) methods signatures added using string extension methods.


using System;					
public static class Program
{	
	public static void Main()
	{
		string dq = "\""; 
		string numbers = "12345";
		
		Console.WriteLine(	dq + numbers.TrimStart(1) 	+ dq ); 
		Console.WriteLine(	dq + numbers.TrimStart(50) 	+ dq ); 
		Console.WriteLine(	dq + numbers.TrimEnd(1)		+ dq ); 
		Console.WriteLine(	dq + numbers.TrimEnd(50) 	+ dq ); 
		Console.WriteLine(	dq + numbers.Truncate(1) 	+ dq ); 
		Console.WriteLine(	dq + numbers.Truncate(50) 	+ dq ); 
		
	}
	
	public static string TrimStart(this string input, int length)
	{
		if (string.IsNullOrEmpty(input) || length < 0) return input;
		
		if (length > input.Length) return input;
		
		return input.Substring(length); 
	}
	public static string TrimEnd(this string input, int length)
	{
		if (string.IsNullOrEmpty(input) || length < 1) return input;
		
		if (length > input.Length) return input;
		
		return input.Substring(0, input.Length - length);
	}

	public static string Truncate(this string value, int maxLength)
    {
        if (string.IsNullOrEmpty(value)) return value;
        return value.Length <= maxLength ? string.Empty : value.Substring(0, maxLength); 
    }
}

Thursday, July 12, 2018

Cleanup Powershell Tracing Directories script

Removes the Poweshell Script Tracing directories, by strictly matching directories in Documents directory that match YYYYMMDD only.


 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
#------------------------------------------------------------------------------------------------------------------------------------------------------------------
# Script: CleanupPowershellTracingDirectories.ps1 
#
# Created by metadataconsult@gmail.com, metadataconsulting.blogspot.ca, 2018
#
# Function: 
#
# Removes the Poweshell Script Tracing directories, by strictly matching directories in documents directory that match YYYYMMDD only.
#
# Warranty: 
#
# The  scripts are provided AS IS without warranty of any kind. 
# Metadata Consulting further disclaims all implied warranties including,  
# without limitation, any implied warranties of merchantability or of fitness for 
# a particular purpose. The entire risk arising out of the use or performance of  
# the  scripts and documentation remains with you. 
# Metadata Consulting, its authors, or anyone else involved in the creation, production, or 
# delivery of the scripts be liable for any damages whatsoever (including, 
# without limitation, damages for loss of business profits, business interruption, 
# loss of business information, or other pecuniary loss) arising out of the use 
# of or inability to use the  scripts or documentation, even if  
# has been advised of the possibility of such damages. 
#------------------------------------------------------------------------------------------------------------------------------------------------------------------

$docfolder = "${Env:USERPROFILE}\Documents"

Write-Host "Listing All Poweshell Script Tracing Directories in folder $docfolder" -ForegroundColor Cyan
# https://stackoverflow.com/questions/4766845/yyyymmdd-date-format-regular-expression-to-validate-a-date-in-c-sharp-net - mactches leap years as well
Get-ChildItem $docfolder | Where {$_.Name -Match "^(?:(?:(?:(?:(?:[13579][26]|[2468][048])00)|(?:[0-9]{2}(?:(?:[13579][26])|(?:[2468][048]|0[48]))))(?:(?:(?:09|04|06|11)(?:0[1-9]|1[0-9]|2[0-9]|30))|(?:(?:01|03|05|07|08|10|12)(?:0[1-9]|1[0-9]|2[0-9]|3[01]))|(?:02(?:0[1-9]|1[0-9]|2[0-9]))))|(?:[0-9]{4}(?:(?:(?:09|04|06|11)(?:0[1-9]|1[0-9]|2[0-9]|30))|(?:(?:01|03|05|07|08|10|12)(?:0[1-9]|1[0-9]|2[0-9]|3[01]))|(?:02(?:[01][0-9]|2[0-8])))))$"}

$title = "Delete Poweshell Script Tracing Directories?"
$message = "Choose default Exit,`nor DELETE Selected Powershell Script Tracing Directories,`nor DELETE SILENT All Powershell Script Tracing Directories.`nThis is permanent delete, there is no recycle-bin recovery."
$msg1 = "Exit" 
$msg2 = "DELETE Selected Script Tracing Directories forever, no recycle bin!"
$msg3 = "DELETE All Silently Script Tracing Directories forever, no recycle bin!"
$one = New-Object System.Management.Automation.Host.ChoiceDescription "&Exit", $msg1 
$two = New-Object System.Management.Automation.Host.ChoiceDescription "&Delete Selected", $msg2
$three = New-Object System.Management.Automation.Host.ChoiceDescription "&Delete Silent", $msg3
$options = [System.Management.Automation.Host.ChoiceDescription[]]($one,$two, $three)
$result = $host.ui.PromptForChoice($title, $message, $options, 0) 

Write-Host ""
switch ($result)
    {
        0 {Write-Host "You selected `n1. $msg1" -ForegroundColor Cyan;}
        1 {Write-Host "You selected `n2. $msg2" -ForegroundColor Cyan;}
        2 {Write-Host "You selected `n3. $msg3" -ForegroundColor Cyan;}
        default {Write-Host "You choose something else. Exiting"; exit}
    }

if ($result -eq 1) {

Get-ChildItem $docfolder | Where {$_.Name -Match "^(?:(?:(?:(?:(?:[13579][26]|[2468][048])00)|(?:[0-9]{2}(?:(?:[13579][26])|(?:[2468][048]|0[48]))))(?:(?:(?:09|04|06|11)(?:0[1-9]|1[0-9]|2[0-9]|30))|(?:(?:01|03|05|07|08|10|12)(?:0[1-9]|1[0-9]|2[0-9]|3[01]))|(?:02(?:0[1-9]|1[0-9]|2[0-9]))))|(?:[0-9]{4}(?:(?:(?:09|04|06|11)(?:0[1-9]|1[0-9]|2[0-9]|30))|(?:(?:01|03|05|07|08|10|12)(?:0[1-9]|1[0-9]|2[0-9]|3[01]))|(?:02(?:[01][0-9]|2[0-8])))))$"} | Remove-Item -ErrorAction Stop
Write-Host "Deleted selected Poweshell Script Tracing Directories in folder $docfolder" -ForegroundColor Yellow
Write-Host "Done" -ForegroundColor Cyan

}
elseif ($result -eq 2) {

Get-ChildItem $docfolder | Where {$_.Name -Match "^(?:(?:(?:(?:(?:[13579][26]|[2468][048])00)|(?:[0-9]{2}(?:(?:[13579][26])|(?:[2468][048]|0[48]))))(?:(?:(?:09|04|06|11)(?:0[1-9]|1[0-9]|2[0-9]|30))|(?:(?:01|03|05|07|08|10|12)(?:0[1-9]|1[0-9]|2[0-9]|3[01]))|(?:02(?:0[1-9]|1[0-9]|2[0-9]))))|(?:[0-9]{4}(?:(?:(?:09|04|06|11)(?:0[1-9]|1[0-9]|2[0-9]|30))|(?:(?:01|03|05|07|08|10|12)(?:0[1-9]|1[0-9]|2[0-9]|3[01]))|(?:02(?:[01][0-9]|2[0-8])))))$"} | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
Write-Host "Deleted all Poweshell Script Tracing Directories in folder $docfolder, errors silently ignored." -ForegroundColor Yellow
Write-Host "Done" -ForegroundColor Cyan

}

Tuesday, July 10, 2018

Windows 10 Create Password Backup Reset Disk Window is Hidden


In Windows 10, I found a bug,  when I tried to run Create a password reset disk for the 1st time, the window is hidden from view. I could Alt-Tab and see it listed but I could not get it into view. 

This is normal way to invoke Create a password reset disk.
  1. Plug your USB drive 
  2. Press Windows key + S on your keyboard to bring up the search bar.
  3. Type Control Panel and open it.
  4. Type in User accounts in Search Control Panel.
  5. Click on User accounts.
  6. Select Create a password reset disk *USB must be present to run
If you can't see the Create a password reset disk Wizard windows. You can try, to cascade windows. But this did not work for me. 




I had to run this manually for me to be able to backup my password. 

Soln: Create a password reset disk from RUN

Open the Run box, type the following and hit Enter to open it directly:
rundll32.exe keymgr.dll,PRShowSaveWizardExW