Private/PrivateFunctions.ps1

function ConvertFrom-Credman {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '')]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingPlainTextForPassword', '')]
    param (
        $CredText
    )
    New-Object PSObject -Property @{
        Target       = $(try {($CredText.Split("`n") -Match 'Target').Split(':')[1].Trim()}catch{''})
        User         = $(try {($CredText.Split("`n") -Match 'UserName').Split(':')[1].Trim()}catch{''})
        Comment      = $(try {($CredText.Split("`n") -Match 'Comment').Split(':')[1].Trim()}catch{''})
        SecurePass   = $(try {ConvertTo-SecureString ($CredText.Split("`n") -Match 'Password').Split(':')[1].Trim() -AsPlainText -Force }catch{$null})
    }
}

<#
.Synopsis
  Provides access to Windows CredMan basic functionality for client scripts
 
****************** IMPORTANT ******************
*
* If you use this script from the PS console, you
* should ALWAYS pass the Target, User and Password
* parameters using single quotes:
*
* .\CredMan.ps1 -AddCred -Target 'http://server' -User 'JoeSchmuckatelli' -Pass 'P@55w0rd!'
*
* to prevent PS misinterpreting special characters
* you might use as PS reserved characters
*
****************** IMPORTANT ******************
 
.Description
  Provides the following API when dot-sourced
  Del-Cred
  Enum-Creds
  Read-Cred
  Write-Cred
 
  Supports the following cmd-line actions
  AddCred (requires -User, -Pass; -Target is optional)
  DelCred (requires -Target)
  GetCred (requires -Target)
  RunTests (no cmd-line opts)
  ShoCred (optional -All parameter to dump cred objects to console)
 
.INPUTS
  See function-level notes
 
.OUTPUTS
  Cmd-line usage: console output relative to success or failure state
  Dot-sourced usage:
  ** Successful Action **
  * Del-Cred : Int = 0
  * Enum-Cred : PsUtils.CredMan+Credential[]
  * Read-Cred : PsUtils.CredMan+Credential
  * Write-Cred : Int = 0
  ** Failure **
  * All API : Management.Automation.ErrorRecord
 
.NOTES
 
  Author: Jim Harrison (jim@isatools.org)
  Date : 2012/05/20
  Vers : 1.5
 
  Updates:
  2012/10/13
          - Fixed a bug where the script would only read, write or delete GENERIC
          credentials types.
                - Added #region blocks to clarify internal functionality
                - Added 'CredType' param to specify what sort of credential is to be read,
                created or deleted (not used for -ShoCred or Enum-Creds)
                - Added 'CredPersist' param to specify how the credential is to be stored;
                only used in Write-Cred
                - Added 'All' param for -ShoCreds to differentiate between creds summary
                list and detailed creds dump
                - Added CRED_FLAGS enum to make the credential struct flags values clearer
                - Improved parameter validation
                - Expanded internal help (used with Get-Help cmdlet)
                - Cmd-line functions better illustrate how to interpret the results when
                dot-sourcing the script
 
.PARAMETER AddCred
    Specifies that you wish to add a new credential or update an existing credentials
    -Target, -User and -Pass parameters are required for this action
 
.PARAMETER Comment
    Specifies the information you wish to place in the credentials comment field
 
.PARAMETER CredPersist
    Specifies the credentials storage persistence you wish to use
    Valid values are: "SESSION", "LOCAL_MACHINE", "ENTERPRISE"
    NOTE: if not specified, defaults to "ENTERPRISE"
 
.PARAMETER CredType
    Specifies the type of credential object you want to store
    Valid values are: "GENERIC", "DOMAIN_PASSWORD", "DOMAIN_CERTIFICATE",
    "DOMAIN_VISIBLE_PASSWORD", "GENERIC_CERTIFICATE", "DOMAIN_EXTENDED",
    "MAXIMUM", "MAXIMUM_EX"
    NOTE: if not specified, defaults to "GENERIC"
    ****************** IMPORTANT ******************
    *
    * I STRONGLY recommend that you become familiar
    * with http://msdn.microsoft.com/en-us/library/windows/desktop/aa374788(v=vs.85).aspx
    * before you create new credentials with -CredType other than "GENERIC"
    *
    ****************** IMPORTANT ******************
 
 
.PARAMETER DelCred
    Specifies that you wish to remove an existing credential
    -CredType may be required to remove the correct credential if more than one is
    specified for a target
 
.PARAMETER GetCred
    Specifies that you wish to retrieve an existing credential
    -CredType may be required to access the correct credential if more than one is
    specified for a target
 
.PARAMETER Pass
    Specifies the credentials password
 
.PARAMETER RunTests
    Specifies that you wish to run built-in Win32 CredMan functionality tests
 
.PARAMETER ShoCred
    Specifies that you wish to retrieve all credential stored for the interactive user
    -All parameter may be used to indicate that you wish to view all credentials properties
    (default display is a summary list)
 
.PARAMETER Target
    Specifies the authentication target for the specified credentials
    If not specified, the -User information is used
 
.PARAMETER User
    Specifies the credentials username
 
 
.LINK
    http://msdn.microsoft.com/en-us/library/windows/desktop/aa374788(v=vs.85).aspx
    http://stackoverflow.com/questions/7162604/get-cached-credentials-in-powershell-from-windows-7-credential-manager
    http://msdn.microsoft.com/en-us/library/windows/desktop/aa374788(v=vs.85).aspx
    http://blogs.msdn.com/b/peerchan/archive/2005/11/01/487834.aspx
 
.EXAMPLE
    .\CredMan.ps1 -AddCred -Target 'http://aserver' -User 'UserName' -Password 'P@55w0rd!' -Comment 'cuziwanna'
    Stores the credential for 'UserName' with a password of 'P@55w0rd!' for authentication against 'http://aserver' and adds a comment of 'cuziwanna'
 
.EXAMPLE
    .\CredMan.ps1 -DelCred -Target 'http://aserver' -CredType 'DOMAIN_PASSWORD'
    Removes the credential used for the target 'http://aserver' as credentials type 'DOMAIN_PASSWORD'
 
.EXAMPLE
    .\CredMan.ps1 -GetCred -Target 'http://aserver'
    Retreives the credential used for the target 'http://aserver'
 
.EXAMPLE
    .\CredMan.ps1 -ShoCred
    Retrieves a summary list of all credentials stored for the interactive user
 
.EXAMPLE
    .\CredMan.ps1 -ShoCred -All
    Retrieves a detailed list of all credentials stored for the interactive user
 
#>


#requires -version 2
function CredMan {
  [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")]
  [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingUsernameAndPasswordParams", "")]
  [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseApprovedVerbs", "")]
  [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSReviewUnusedParameter", "")]
  [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "")]
  Param
  (
    [Parameter(Mandatory = $false)][Switch] $AddCred,
    [Parameter(Mandatory = $false)][Switch] $DelCred,
    [Parameter(Mandatory = $false)][Switch] $GetCred,
    [Parameter(Mandatory = $false)][Switch] $ShoCred,
    [Parameter(Mandatory = $false)][Switch] $RunTests,
    [Parameter(Mandatory = $false)][ValidateLength(1, 32767) <# CRED_MAX_GENERIC_TARGET_NAME_LENGTH #>][String] $Target,
    [Parameter(Mandatory = $false)][ValidateLength(1, 512) <# CRED_MAX_USERNAME_LENGTH #>][String] $User,
    [Parameter(Mandatory = $false)][ValidateLength(1, 512) <# CRED_MAX_CREDENTIAL_BLOB_SIZE #>][String] $Pass,
    [Parameter(Mandatory = $false)][ValidateLength(1, 256) <# CRED_MAX_STRING_LENGTH #>][String] $Comment,
    [Parameter(Mandatory = $false)][Switch] $All,
    [Parameter(Mandatory = $false)][ValidateSet("GENERIC",
      "DOMAIN_PASSWORD",
      "DOMAIN_CERTIFICATE",
      "DOMAIN_VISIBLE_PASSWORD",
      "GENERIC_CERTIFICATE",
      "DOMAIN_EXTENDED",
      "MAXIMUM",
      "MAXIMUM_EX")][String] $CredType = "GENERIC",
    [Parameter(Mandatory = $false)][ValidateSet("SESSION",
      "LOCAL_MACHINE",
      "ENTERPRISE")][String] $CredPersist = "ENTERPRISE"
  )

  #region Pinvoke
  #region Inline C#
  [String] $PsCredmanUtils = @"
using System;
using System.Runtime.InteropServices;
 
namespace PsUtils
{
    public class CredMan
    {
        #region Imports
        // DllImport derives from System.Runtime.InteropServices
        [DllImport("Advapi32.dll", SetLastError = true, EntryPoint = "CredDeleteW", CharSet = CharSet.Unicode)]
        private static extern bool CredDeleteW([In] string target, [In] CRED_TYPE type, [In] int reservedFlag);
 
        [DllImport("Advapi32.dll", SetLastError = true, EntryPoint = "CredEnumerateW", CharSet = CharSet.Unicode)]
        private static extern bool CredEnumerateW([In] string Filter, [In] int Flags, out int Count, out IntPtr CredentialPtr);
 
        [DllImport("Advapi32.dll", SetLastError = true, EntryPoint = "CredFree")]
        private static extern void CredFree([In] IntPtr cred);
 
        [DllImport("Advapi32.dll", SetLastError = true, EntryPoint = "CredReadW", CharSet = CharSet.Unicode)]
        private static extern bool CredReadW([In] string target, [In] CRED_TYPE type, [In] int reservedFlag, out IntPtr CredentialPtr);
 
        [DllImport("Advapi32.dll", SetLastError = true, EntryPoint = "CredWriteW", CharSet = CharSet.Unicode)]
        private static extern bool CredWriteW([In] ref Credential userCredential, [In] UInt32 flags);
        #endregion
 
        #region Fields
        public enum CRED_FLAGS : uint
        {
            NONE = 0x0,
            PROMPT_NOW = 0x2,
            USERNAME_TARGET = 0x4
        }
 
        public enum CRED_ERRORS : uint
        {
            ERROR_SUCCESS = 0x0,
            ERROR_INVALID_PARAMETER = 0x80070057,
            ERROR_INVALID_FLAGS = 0x800703EC,
            ERROR_NOT_FOUND = 0x80070490,
            ERROR_NO_SUCH_LOGON_SESSION = 0x80070520,
            ERROR_BAD_USERNAME = 0x8007089A
        }
 
        public enum CRED_PERSIST : uint
        {
            SESSION = 1,
            LOCAL_MACHINE = 2,
            ENTERPRISE = 3
        }
 
        public enum CRED_TYPE : uint
        {
            GENERIC = 1,
            DOMAIN_PASSWORD = 2,
            DOMAIN_CERTIFICATE = 3,
            DOMAIN_VISIBLE_PASSWORD = 4,
            GENERIC_CERTIFICATE = 5,
            DOMAIN_EXTENDED = 6,
            MAXIMUM = 7, // Maximum supported cred type
            MAXIMUM_EX = (MAXIMUM + 1000), // Allow new applications to run on old OSes
        }
 
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public struct Credential
        {
            public CRED_FLAGS Flags;
            public CRED_TYPE Type;
            public string TargetName;
            public string Comment;
            public DateTime LastWritten;
            public UInt32 CredentialBlobSize;
            public string CredentialBlob;
            public CRED_PERSIST Persist;
            public UInt32 AttributeCount;
            public IntPtr Attributes;
            public string TargetAlias;
            public string UserName;
        }
 
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        private struct NativeCredential
        {
            public CRED_FLAGS Flags;
            public CRED_TYPE Type;
            public IntPtr TargetName;
            public IntPtr Comment;
            public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
            public UInt32 CredentialBlobSize;
            public IntPtr CredentialBlob;
            public UInt32 Persist;
            public UInt32 AttributeCount;
            public IntPtr Attributes;
            public IntPtr TargetAlias;
            public IntPtr UserName;
        }
        #endregion
 
        #region Child Class
        private class CriticalCredentialHandle : Microsoft.Win32.SafeHandles.CriticalHandleZeroOrMinusOneIsInvalid
        {
            public CriticalCredentialHandle(IntPtr preexistingHandle)
            {
                SetHandle(preexistingHandle);
            }
 
            private Credential XlateNativeCred(IntPtr pCred)
            {
                NativeCredential ncred = (NativeCredential)Marshal.PtrToStructure(pCred, typeof(NativeCredential));
                Credential cred = new Credential();
                cred.Type = ncred.Type;
                cred.Flags = ncred.Flags;
                cred.Persist = (CRED_PERSIST)ncred.Persist;
 
                long LastWritten = ncred.LastWritten.dwHighDateTime;
                LastWritten = (LastWritten << 32) + ncred.LastWritten.dwLowDateTime;
                cred.LastWritten = DateTime.FromFileTime(LastWritten);
 
                cred.UserName = Marshal.PtrToStringUni(ncred.UserName);
                cred.TargetName = Marshal.PtrToStringUni(ncred.TargetName);
                cred.TargetAlias = Marshal.PtrToStringUni(ncred.TargetAlias);
                cred.Comment = Marshal.PtrToStringUni(ncred.Comment);
                cred.CredentialBlobSize = ncred.CredentialBlobSize;
                if (0 < ncred.CredentialBlobSize)
                {
                    cred.CredentialBlob = Marshal.PtrToStringUni(ncred.CredentialBlob, (int)ncred.CredentialBlobSize / 2);
                }
                return cred;
            }
 
            public Credential GetCredential()
            {
                if (IsInvalid)
                {
                    throw new InvalidOperationException("Invalid CriticalHandle!");
                }
                Credential cred = XlateNativeCred(handle);
                return cred;
            }
 
            public Credential[] GetCredentials(int count)
            {
                if (IsInvalid)
                {
                    throw new InvalidOperationException("Invalid CriticalHandle!");
                }
                Credential[] Credentials = new Credential[count];
                IntPtr pTemp = IntPtr.Zero;
                for (int inx = 0; inx < count; inx++)
                {
                    pTemp = Marshal.ReadIntPtr(handle, inx * IntPtr.Size);
                    Credential cred = XlateNativeCred(pTemp);
                    Credentials[inx] = cred;
                }
                return Credentials;
            }
 
            override protected bool ReleaseHandle()
            {
                if (IsInvalid)
                {
                    return false;
                }
                CredFree(handle);
                SetHandleAsInvalid();
                return true;
            }
        }
        #endregion
 
        #region Custom API
        public static int CredDelete(string target, CRED_TYPE type)
        {
            if (!CredDeleteW(target, type, 0))
            {
                return Marshal.GetHRForLastWin32Error();
            }
            return 0;
        }
 
        public static int CredEnum(string Filter, out Credential[] Credentials)
        {
            int count = 0;
            int Flags = 0x0;
            if (string.IsNullOrEmpty(Filter) ||
                "*" == Filter)
            {
                Filter = null;
                if (6 <= Environment.OSVersion.Version.Major)
                {
                    Flags = 0x1; //CRED_ENUMERATE_ALL_CREDENTIALS; only valid is OS >= Vista
                }
            }
            IntPtr pCredentials = IntPtr.Zero;
            if (!CredEnumerateW(Filter, Flags, out count, out pCredentials))
            {
                Credentials = null;
                return Marshal.GetHRForLastWin32Error();
            }
            CriticalCredentialHandle CredHandle = new CriticalCredentialHandle(pCredentials);
            Credentials = CredHandle.GetCredentials(count);
            return 0;
        }
 
        public static int CredRead(string target, CRED_TYPE type, out Credential Credential)
        {
            IntPtr pCredential = IntPtr.Zero;
            Credential = new Credential();
            if (!CredReadW(target, type, 0, out pCredential))
            {
                return Marshal.GetHRForLastWin32Error();
            }
            CriticalCredentialHandle CredHandle = new CriticalCredentialHandle(pCredential);
            Credential = CredHandle.GetCredential();
            return 0;
        }
 
        public static int CredWrite(Credential userCredential)
        {
            if (!CredWriteW(ref userCredential, 0))
            {
                return Marshal.GetHRForLastWin32Error();
            }
            return 0;
        }
 
        #endregion
 
        private static int AddCred()
        {
            Credential Cred = new Credential();
            string Password = "Password";
            Cred.Flags = 0;
            Cred.Type = CRED_TYPE.GENERIC;
            Cred.TargetName = "Target";
            Cred.UserName = "UserName";
            Cred.AttributeCount = 0;
            Cred.Persist = CRED_PERSIST.ENTERPRISE;
            Cred.CredentialBlobSize = (uint)Password.Length;
            Cred.CredentialBlob = Password;
            Cred.Comment = "Comment";
            return CredWrite(Cred);
        }
 
        private static bool CheckError(string TestName, CRED_ERRORS Rtn)
        {
            switch(Rtn)
            {
                case CRED_ERRORS.ERROR_SUCCESS:
                    Console.WriteLine(string.Format("'{0}' worked", TestName));
                    return true;
                case CRED_ERRORS.ERROR_INVALID_FLAGS:
                case CRED_ERRORS.ERROR_INVALID_PARAMETER:
                case CRED_ERRORS.ERROR_NO_SUCH_LOGON_SESSION:
                case CRED_ERRORS.ERROR_NOT_FOUND:
                case CRED_ERRORS.ERROR_BAD_USERNAME:
                    Console.WriteLine(string.Format("'{0}' failed; {1}.", TestName, Rtn));
                    break;
                default:
                    Console.WriteLine(string.Format("'{0}' failed; 0x{1}.", TestName, Rtn.ToString("X")));
                    break;
            }
            return false;
        }
 
        /*
         * Note: the Main() function is primarily for debugging and testing in a Visual
         * Studio session. Although it will work from PowerShell, it's not very useful.
         */
        public static void Main()
        {
            Credential[] Creds = null;
            Credential Cred = new Credential();
            int Rtn = 0;
 
            Console.WriteLine("Testing CredWrite()");
            Rtn = AddCred();
            if (!CheckError("CredWrite", (CRED_ERRORS)Rtn))
            {
                return;
            }
            Console.WriteLine("Testing CredEnum()");
            Rtn = CredEnum(null, out Creds);
            if (!CheckError("CredEnum", (CRED_ERRORS)Rtn))
            {
                return;
            }
            Console.WriteLine("Testing CredRead()");
            Rtn = CredRead("Target", CRED_TYPE.GENERIC, out Cred);
            if (!CheckError("CredRead", (CRED_ERRORS)Rtn))
            {
                return;
            }
            Console.WriteLine("Testing CredDelete()");
            Rtn = CredDelete("Target", CRED_TYPE.GENERIC);
            if (!CheckError("CredDelete", (CRED_ERRORS)Rtn))
            {
                return;
            }
            Console.WriteLine("Testing CredRead() again");
            Rtn = CredRead("Target", CRED_TYPE.GENERIC, out Cred);
            if (!CheckError("CredRead", (CRED_ERRORS)Rtn))
            {
                Console.WriteLine("if the error is 'ERROR_NOT_FOUND', this result is OK.");
            }
        }
    }
}
"@

  #endregion

  $PsCredMan = $null
  try {
    $PsCredMan = [PsUtils.CredMan]
  }
  catch {
    #only remove the error we generate
    If ($Error.Count){
      $Error.RemoveAt($Error.Count - 1)
    } else {
      $Error.Clear()
    }
  }
  if ($null -eq $PsCredMan) {
    Add-Type $PsCredmanUtils
  }
  #endregion

  #region Internal Tools
  [HashTable] $ErrorCategory = @{0x80070057 = "InvalidArgument";
    0x800703EC                              = "InvalidData";
    0x80070490                              = "ObjectNotFound";
    0x80070520                              = "SecurityError";
    0x8007089A                              = "SecurityError"
  }

  function Get-CredType {
    Param
    (
      [Parameter(Mandatory = $true)][ValidateSet("GENERIC",
        "DOMAIN_PASSWORD",
        "DOMAIN_CERTIFICATE",
        "DOMAIN_VISIBLE_PASSWORD",
        "GENERIC_CERTIFICATE",
        "DOMAIN_EXTENDED",
        "MAXIMUM",
        "MAXIMUM_EX")][String] $CredType
    )

    switch ($CredType) {
      "GENERIC" { return [PsUtils.CredMan+CRED_TYPE]::GENERIC }
      "DOMAIN_PASSWORD" { return [PsUtils.CredMan+CRED_TYPE]::DOMAIN_PASSWORD }
      "DOMAIN_CERTIFICATE" { return [PsUtils.CredMan+CRED_TYPE]::DOMAIN_CERTIFICATE }
      "DOMAIN_VISIBLE_PASSWORD" { return [PsUtils.CredMan+CRED_TYPE]::DOMAIN_VISIBLE_PASSWORD }
      "GENERIC_CERTIFICATE" { return [PsUtils.CredMan+CRED_TYPE]::GENERIC_CERTIFICATE }
      "DOMAIN_EXTENDED" { return [PsUtils.CredMan+CRED_TYPE]::DOMAIN_EXTENDED }
      "MAXIMUM" { return [PsUtils.CredMan+CRED_TYPE]::MAXIMUM }
      "MAXIMUM_EX" { return [PsUtils.CredMan+CRED_TYPE]::MAXIMUM_EX }
    }
  }

  function Get-CredPersist {
    Param
    (
      [Parameter(Mandatory = $true)][ValidateSet("SESSION",
        "LOCAL_MACHINE",
        "ENTERPRISE")][String] $CredPersist
    )

    switch ($CredPersist) {
      "SESSION" { return [PsUtils.CredMan+CRED_PERSIST]::SESSION }
      "LOCAL_MACHINE" { return [PsUtils.CredMan+CRED_PERSIST]::LOCAL_MACHINE }
      "ENTERPRISE" { return [PsUtils.CredMan+CRED_PERSIST]::ENTERPRISE }
    }
  }
  #endregion

  #region Dot-Sourced API
  function Del-Creds {
    <#
.Synopsis
  Deletes the specified credentials
 
.Description
  Calls Win32 CredDeleteW via [PsUtils.CredMan]::CredDelete
 
.INPUTS
  See function-level notes
 
.OUTPUTS
  0 or non-0 according to action success
  [Management.Automation.ErrorRecord] if error encountered
 
.PARAMETER Target
  Specifies the URI for which the credentials are associated
 
.PARAMETER CredType
  Specifies the desired credentials type; defaults to
  "CRED_TYPE_GENERIC"
#>


    Param
    (
      [Parameter(Mandatory = $true)][ValidateLength(1, 32767)][String] $Target,
      [Parameter(Mandatory = $false)][ValidateSet("GENERIC",
        "DOMAIN_PASSWORD",
        "DOMAIN_CERTIFICATE",
        "DOMAIN_VISIBLE_PASSWORD",
        "GENERIC_CERTIFICATE",
        "DOMAIN_EXTENDED",
        "MAXIMUM",
        "MAXIMUM_EX")][String] $CredType = "GENERIC"
    )

    [Int] $Results = 0
    try {
      $Results = [PsUtils.CredMan]::CredDelete($Target, $(Get-CredType $CredType))
    }
    catch {
      return $_
    }
    if (0 -ne $Results) {
      [String] $Msg = "Failed to delete credentials store for target '$Target'"
      [Management.ManagementException] $MgmtException = New-Object Management.ManagementException($Msg)
      [Management.Automation.ErrorRecord] $ErrRcd = New-Object Management.Automation.ErrorRecord($MgmtException, $Results.ToString("X"), $ErrorCategory[$Results], $null)
      return $ErrRcd
    }
    return $Results
  }

  function Enum-Creds {
    <#
.Synopsis
  Enumerates stored credentials for operating user
 
.Description
  Calls Win32 CredEnumerateW via [PsUtils.CredMan]::CredEnum
 
.INPUTS
 
 
.OUTPUTS
  [PsUtils.CredMan+Credential[]] if successful
  [Management.Automation.ErrorRecord] if unsuccessful or error encountered
 
.PARAMETER Filter
  Specifies the filter to be applied to the query
  Defaults to [String]::Empty
 
#>


    Param
    (
      [Parameter(Mandatory = $false)][AllowEmptyString()][String] $Filter = [String]::Empty
    )

    [PsUtils.CredMan+Credential[]] $Creds = [Array]::CreateInstance([PsUtils.CredMan+Credential], 0)
    [Int] $Results = 0
    try {
      $Results = [PsUtils.CredMan]::CredEnum($Filter, [Ref]$Creds)
    }
    catch {
      return $_
    }
    switch ($Results) {
      0 { break }
      0x80070490 { break } #ERROR_NOT_FOUND
      default {
        [String] $Msg = "Failed to enumerate credentials store for user '$Env:UserName'"
        [Management.ManagementException] $MgmtException = New-Object Management.ManagementException($Msg)
        [Management.Automation.ErrorRecord] $ErrRcd = New-Object Management.Automation.ErrorRecord($MgmtException, $Results.ToString("X"), $ErrorCategory[$Results], $null)
        return $ErrRcd
      }
    }
    return $Creds
  }

  function Read-Creds {
    <#
.Synopsis
  Reads specified credentials for operating user
 
.Description
  Calls Win32 CredReadW via [PsUtils.CredMan]::CredRead
 
.INPUTS
 
.OUTPUTS
  [PsUtils.CredMan+Credential] if successful
  [Management.Automation.ErrorRecord] if unsuccessful or error encountered
 
.PARAMETER Target
  Specifies the URI for which the credentials are associated
  If not provided, the username is used as the target
 
.PARAMETER CredType
  Specifies the desired credentials type; defaults to
  "CRED_TYPE_GENERIC"
#>


    Param
    (
      [Parameter(Mandatory = $true)][ValidateLength(1, 32767)][String] $Target,
      [Parameter(Mandatory = $false)][ValidateSet("GENERIC",
        "DOMAIN_PASSWORD",
        "DOMAIN_CERTIFICATE",
        "DOMAIN_VISIBLE_PASSWORD",
        "GENERIC_CERTIFICATE",
        "DOMAIN_EXTENDED",
        "MAXIMUM",
        "MAXIMUM_EX")][String] $CredType = "GENERIC"
    )

    if ("GENERIC" -ne $CredType -and 337 -lt $Target.Length) { #CRED_MAX_DOMAIN_TARGET_NAME_LENGTH
      [String] $Msg = "Target field is longer ($($Target.Length)) than allowed (max 337 characters)"
      [Management.ManagementException] $MgmtException = New-Object Management.ManagementException($Msg)
      [Management.Automation.ErrorRecord] $ErrRcd = New-Object Management.Automation.ErrorRecord($MgmtException, 666, 'LimitsExceeded', $null)
      return $ErrRcd
    }
    [PsUtils.CredMan+Credential] $Cred = New-Object PsUtils.CredMan+Credential
    [Int] $Results = 0
    try {
      $Results = [PsUtils.CredMan]::CredRead($Target, $(Get-CredType $CredType), [Ref]$Cred)
    }
    catch {
      return $_
    }

    switch ($Results) {
      0 { break }
      0x80070490 { return $null } #ERROR_NOT_FOUND
      default {
        [String] $Msg = "Error reading credentials for target '$Target' from '$Env:UserName' credentials store"
        [Management.ManagementException] $MgmtException = New-Object Management.ManagementException($Msg)
        [Management.Automation.ErrorRecord] $ErrRcd = New-Object Management.Automation.ErrorRecord($MgmtException, $Results.ToString("X"), $ErrorCategory[$Results], $null)
        return $ErrRcd
      }
    }
    return $Cred
  }

  function Write-Creds {
    <#
.Synopsis
  Saves or updates specified credentials for operating user
 
.Description
  Calls Win32 CredWriteW via [PsUtils.CredMan]::CredWrite
 
.INPUTS
 
.OUTPUTS
  [Boolean] true if successful
  [Management.Automation.ErrorRecord] if unsuccessful or error encountered
 
.PARAMETER Target
  Specifies the URI for which the credentials are associated
  If not provided, the username is used as the target
 
.PARAMETER UserName
  Specifies the name of credential to be read
 
.PARAMETER Password
  Specifies the password of credential to be read
 
.PARAMETER Comment
  Allows the caller to specify the comment associated with
  these credentials
 
.PARAMETER CredType
  Specifies the desired credentials type; defaults to
  "CRED_TYPE_GENERIC"
 
.PARAMETER CredPersist
  Specifies the desired credentials storage type;
  defaults to "CRED_PERSIST_ENTERPRISE"
#>


    Param
    (
      [Parameter(Mandatory = $false)][ValidateLength(0, 32676)][String] $Target,
      [Parameter(Mandatory = $true)][ValidateLength(1, 512)][String] $UserName,
      [Parameter(Mandatory = $true)][ValidateLength(1, 512)][String] $Password,
      [Parameter(Mandatory = $false)][ValidateLength(0, 256)][String] $Comment = [String]::Empty,
      [Parameter(Mandatory = $false)][ValidateSet("GENERIC",
        "DOMAIN_PASSWORD",
        "DOMAIN_CERTIFICATE",
        "DOMAIN_VISIBLE_PASSWORD",
        "GENERIC_CERTIFICATE",
        "DOMAIN_EXTENDED",
        "MAXIMUM",
        "MAXIMUM_EX")][String] $CredType = "GENERIC",
      [Parameter(Mandatory = $false)][ValidateSet("SESSION",
        "LOCAL_MACHINE",
        "ENTERPRISE")][String] $CredPersist = "ENTERPRISE"
    )

    if ([String]::IsNullOrEmpty($Target)) {
      $Target = $UserName
    }
    if ("GENERIC" -ne $CredType -and 337 -lt $Target.Length) { #CRED_MAX_DOMAIN_TARGET_NAME_LENGTH
      [String] $Msg = "Target field is longer ($($Target.Length)) than allowed (max 337 characters)"
      [Management.ManagementException] $MgmtException = New-Object Management.ManagementException($Msg)
      [Management.Automation.ErrorRecord] $ErrRcd = New-Object Management.Automation.ErrorRecord($MgmtException, 666, 'LimitsExceeded', $null)
      return $ErrRcd
    }
    if ([String]::IsNullOrEmpty($Comment)) {
      $Comment = [String]::Format("Last edited by {0}\{1} on {2}",
        $Env:UserDomain,
        $Env:UserName,
        $Env:ComputerName)
    }
    #[String] $DomainName = [Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties().DomainName
    [PsUtils.CredMan+Credential] $Cred = New-Object PsUtils.CredMan+Credential
    switch ($Target -eq $UserName -and
      ("CRED_TYPE_DOMAIN_PASSWORD" -eq $CredType -or
        "CRED_TYPE_DOMAIN_CERTIFICATE" -eq $CredType)) {
      $true { $Cred.Flags = [PsUtils.CredMan+CRED_FLAGS]::USERNAME_TARGET }
      $false { $Cred.Flags = [PsUtils.CredMan+CRED_FLAGS]::NONE }
    }
    $Cred.Type = Get-CredType $CredType
    $Cred.TargetName = $Target
    $Cred.UserName = $UserName
    $Cred.AttributeCount = 0
    $Cred.Persist = Get-CredPersist $CredPersist
    $Cred.CredentialBlobSize = [Text.Encoding]::Unicode.GetBytes($Password).Length
    $Cred.CredentialBlob = $Password
    $Cred.Comment = $Comment

    [Int] $Results = 0
    try {
      $Results = [PsUtils.CredMan]::CredWrite($Cred)
    }
    catch {
      return $_
    }

    if (0 -ne $Results) {
      [String] $Msg = "Failed to write to credentials store for target '$Target' using '$UserName', '$Password', '$Comment'"
      [Management.ManagementException] $MgmtException = New-Object Management.ManagementException($Msg)
      [Management.Automation.ErrorRecord] $ErrRcd = New-Object Management.Automation.ErrorRecord($MgmtException, $Results.ToString("X"), $ErrorCategory[$Results], $null)
      return $ErrRcd
    }
    return $Results
  }

  #endregion

  #region Cmd-Line functionality
  function CredManMain {
    #region Adding credentials
    if ($AddCred) {
      if ([String]::IsNullOrEmpty($User) -or
        [String]::IsNullOrEmpty($Pass)) {
        Write-Output "You must supply a user name and password (target URI is optional)."
        return
      }
      # may be [Int32] or [Management.Automation.ErrorRecord]
      [Object] $Results = Write-Creds -Target $Target -UserName $User -Password $Pass -Comment $Comment -CredType $CredType -CredPersist $CredPersist
      if (0 -eq $Results) {
        [Object] $Cred = Read-Creds $Target $CredType
        if ($null -eq $Cred) {
          Write-Output "Credentials for '$Target', '$User' was not found."
          return
        }
        if ($Cred -is [Management.Automation.ErrorRecord]) {
          return $Cred
        }
        [String] $CredStr = @"
Successfully wrote or updated credentials as:
  UserName : $($Cred.UserName)
  Password : $($Cred.CredentialBlob)
  Target : $($Cred.TargetName.Substring($Cred.TargetName.IndexOf("=")+1))
  Updated : $([String]::Format("{0:yyyy-MM-dd HH:mm:ss}", $Cred.LastWritten.ToUniversalTime())) UTC
  Comment : $($Cred.Comment)
"@

        Write-Output $CredStr
        return
      }
      # will be a [Management.Automation.ErrorRecord]
      return $Results
    }
    #endregion

    #region Removing credentials
    if ($DelCred) {
      if (-not $Target) {
        Write-Output "You must supply a target URI."
        return
      }
      # may be [Int32] or [Management.Automation.ErrorRecord]
      [Object] $Results = Del-Creds $Target $CredType
      if (0 -eq $Results) {
        Write-Output "Successfully deleted credentials for '$Target'"
        return
      }
      # will be a [Management.Automation.ErrorRecord]
      return $Results
    }
    #endregion

    #region Reading selected credential
    if ($GetCred) {
      if (-not $Target) {
        Write-Output "You must supply a target URI."
        return
      }
      # may be [PsUtils.CredMan+Credential] or [Management.Automation.ErrorRecord]
      [Object] $Cred = Read-Creds $Target $CredType
      if ($null -eq $Cred) {
        Write-Output "Credential for '$Target' as '$CredType' type was not found."
        return
      }
      if ($Cred -is [Management.Automation.ErrorRecord]) {
        return $Cred
      }
      [String] $CredStr = @"
Found credentials as:
  UserName : $($Cred.UserName)
  Password : $($Cred.CredentialBlob)
  Target : $($Cred.TargetName.Substring($Cred.TargetName.IndexOf("=")+1))
  Updated : $([String]::Format("{0:yyyy-MM-dd HH:mm:ss}", $Cred.LastWritten.ToUniversalTime())) UTC
  Comment : $($Cred.Comment)
"@

      Write-Output $CredStr
    }
    #endregion

    #region Reading all credentials
    if ($ShoCred) {
      # may be [PsUtils.CredMan+Credential[]] or [Management.Automation.ErrorRecord]
      [Object] $Creds = Enum-Creds
      if ($Creds -split [Array] -and 0 -eq $Creds.Length) {
        Write-Output "No Credentials found for $($Env:UserName)"
        return
      }
      if ($Creds -is [Management.Automation.ErrorRecord]) {
        return $Creds
      }
      foreach ($Cred in $Creds) {
        [String] $CredStr = @"
 
UserName : $($Cred.UserName)
Password : $($Cred.CredentialBlob)
Target : $($Cred.TargetName.Substring($Cred.TargetName.IndexOf("=")+1))
Updated : $([String]::Format("{0:yyyy-MM-dd HH:mm:ss}", $Cred.LastWritten.ToUniversalTime())) UTC
Comment : $($Cred.Comment)
"@

        if ($All) {
          $CredStr = @"
$CredStr
Alias : $($Cred.TargetAlias)
AttribCnt : $($Cred.AttributeCount)
Attribs : $($Cred.Attributes)
Flags : $($Cred.Flags)
Pwd Size : $($Cred.CredentialBlobSize)
Storage : $($Cred.Persist)
Type : $($Cred.Type)
"@

        }
        Write-Output $CredStr
      }
      return
    }
    #endregion

    #region Run basic diagnostics
    if ($RunTests) {
      [PsUtils.CredMan]::Main()
    }
    #endregion
  }
  #endregion

  CredManMain
}

function Get-MSIInfo {
    param(
        [parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.IO.FileInfo]$Path,

        [parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [ValidateSet("ProductCode", "UpgradeCode", "ProductVersion", "ProductName", "Manufacturer", "ProductLanguage", "FullVersion")]
        [string]$Property
    )
    Process {
        try {
            # Read property from MSI database
            $WindowsInstaller = New-Object -ComObject WindowsInstaller.Installer
            $MSIDatabase = $WindowsInstaller.GetType().InvokeMember("OpenDatabase", "InvokeMethod", $null, $WindowsInstaller, @($Path.FullName, 0))
            $Query = "SELECT Value FROM Property WHERE Property = '$($Property)'"
            $View = $MSIDatabase.GetType().InvokeMember("OpenView", "InvokeMethod", $null, $MSIDatabase, ($Query))
            $View.GetType().InvokeMember("Execute", "InvokeMethod", $null, $View, $null)
            $Record = $View.GetType().InvokeMember("Fetch", "InvokeMethod", $null, $View, $null)
            $Value = $Record.GetType().InvokeMember("StringData", "GetProperty", $null, $Record, 1)
            # Commit database and close view
            $MSIDatabase.GetType().InvokeMember("Commit", "InvokeMethod", $null, $MSIDatabase, $null)
            $View.GetType().InvokeMember("Close", "InvokeMethod", $null, $View, $null)
            $MSIDatabase = $null
            $View = $null
            # Return the value return
            $Value
        }
        catch {
            Write-Warning -Message $_.Exception.Message
        }
        finally {
            # Run garbage collection and release ComObject
            [System.Runtime.Interopservices.Marshal]::ReleaseComObject($WindowsInstaller) | Out-Null
            [System.GC]::Collect()
        }
    }
    End {

    }

}

function Get-DefaultScriptDataFolder {
    (Split-Path $PROFILE.CurrentUserAllHosts -Parent)
}

function Get-ParameterDefaultValue ([System.Management.Automation.Language.ParameterAst]$paramast) {
    # Evaluate Defined Default
    $m = Select-String -InputObject $paramast.DefaultValue -Pattern '\$(?''Variable''[\w\d]+)' -AllMatches
    $VariableNames = $m.matches.Groups |
    Where Name -eq Variable |
    Select -ExpandProperty Value |
    Sort-Object |
    Get-Unique


    if ($VariableNames) {
        foreach ($var in $VariableNames) {
            #Write-Host "Retrieve Value $($match.Value)"
            if ($PSCmdlet) {
                $ScriptValue = $PSCmdlet.SessionState.PSVariable.GetValue($var)
                if ($ScriptValue) {
                    Set-Variable -Name $var  -Scope 0 -Value $ScriptValue
                }
            }
        }
    }
    if ($paramast.DefaultValue) {
        $Exp = Invoke-Expression $paramast.DefaultValue
        $Exp
    }
}
function Get-ParameterDataFile ([System.Management.Automation.Language.ParameterAst]$paramast, $scriptDataFolder = (Get-DefaultScriptDataFolder)) {
    $paramName = $paramast.Name.ToString().Replace('$', '')
    Join-Path $scriptDataFolder "$paramName.xml"
}
function Get-ParameterSavedValue ([System.Management.Automation.Language.ParameterAst]$paramast, $scriptDataFolder = (Get-DefaultScriptDataFolder)) {
    $ParamDataFile = Get-ParameterDataFile $paramast $scriptDataFolder
    if (Test-Path -Path $ParamDataFile -PathType Leaf) {
        Import-Clixml $ParamDataFile -ErrorAction SilentlyContinue
    }
}
function Get-ParameterScriptValue([System.Management.Automation.Language.ParameterAst]$paramast) {
    $paramName = $paramast.Name.ToString().Replace('$', '')
    if ($PSCmdlet) {
        Set-Variable $paramName $PSCmdlet.SessionState.PSVariable.GetValue($paramName) -Scope 0
    }
    Get-Variable -ValueOnly $paramName -ErrorAction SilentlyContinue
}
function Get-ParameterEnvironmentValue([System.Management.Automation.Language.ParameterAst]$paramast) {
    $paramName = $paramast.Name.ToString().Replace('$', '')
    Get-EnvironmentVariable $paramName
}
function Test-ParameterIsEnvironmentValue([System.Management.Automation.Language.ParameterAst]$paramast) {
    $paramName = $paramast.Name.ToString().Replace('$', '')
    if (([System.Environment]::GetEnvironmentVariable($paramName)) -or (
            $paramast.Attributes | Where { $_.TypeName.ToString() -eq 'Alias' -and ($_.PositionalArguments | Where { $_.Value -Like 'Env*' }) }
        )) {
        $true
    }
    else {
        $false
    }
}

function Get-ParameterCredentialManager([System.Management.Automation.Language.ParameterAst]$paramast) {
    $paramName = $paramast.Name.ToString().Replace('$', '')
    if ($paramast.StaticType.Name -ne [System.Security.SecureString]) {
        Return $null
    }
    # $user = $paramast.Attributes.PositionalArguments | Where Value -like 'Usr*' | Select-Object -ExpandProperty Value
    # $target = $paramast.Attributes.PositionalArguments | Where Value -like 'Tgt*' | Select-Object -ExpandProperty Value
    #if ($user -or $target) {
    (Get-CredentialManagerCredential -Target $paramName).SecurePass
    #}
}

function Get-ParameterDefault([System.Management.Automation.Language.ParameterAst]$paramast, $scriptDataFolder = (Get-DefaultScriptDataFolder)) {
    if (!($value = Get-ParameterScriptValue($paramast)) -or !(Test-ParameterValidationAst -ParamAst $paramast -Value $value)) {
        if (!($value = Get-ParameterCredentialManager($paramast)) -or !(Test-ParameterValidationAst -ParamAst $paramast -Value $value)) {
            if (!($value = Get-ParameterEnvironmentValue($paramast)) -or !(Test-ParameterValidationAst -ParamAst $paramast -Value $value)) {
                if (!($value = Get-ParameterSavedValue $paramast $scriptDataFolder ) -or !(Test-ParameterValidationAst -ParamAst $paramast -Value $value)) {
                    $value = Get-ParameterDefaultValue($paramast)
                }
            }
        }
    }
    $value -as $paramast.StaticType
}
function Save-ParameterValue([System.Management.Automation.Language.ParameterAst]$paramast, $scriptDataFolder = (Get-DefaultScriptDataFolder)) {
    $Name = $paramast.Name.ToString().Replace('$', '')
    $Value = Get-ParameterScriptValue($paramast)
    if ($paramast.StaticType -eq [System.Security.SecureString]) {
        $null = Set-CredentialManagerCredential -Target $Name -Pass $Value -Comment "ScriptParameter"
    }
    else {
        if (Test-ParameterIsEnvironmentValue($paramast)) {
            if ($Value.ToString() -ne (Get-EnvironmentVariable $Name)) {
                Write-Log -Level WARNING -Message "Setting Environment Value {0}:{1}" -Arguments $Name, $Value
                Set-EnvironmentVariable -Name $Name -Value $Value.ToString()
            }
        }
        else {
            $file = (Get-ParameterDataFile $paramast $scriptDataFolder)
            try {
                $xmlValue = Import-Clixml -Path $file -ErrorAction SilentlyContinue
            }
            catch {
                $xmlValue = $null
            }
            if ($Value -ne ($xmlValue)) {
                Write-Log -Level WARNING -Message "Setting Environment Value {0}:{1}" -Arguments $Name, $Value
                Export-Clixml -Path $file -InputObject $Value
            }
        }
    }
}


function Test-ParameterValidationAst {
    [CmdletBinding()]
    [OutputType([bool])]
    param (
        [System.Management.Automation.Language.ParameterAst]$paramast,
        [System.Management.Automation.ParameterMetadata]$Param,
        [System.Object]$Value
    )

    $SetAttribute = $Paramast.Attributes | Where-Object { $_.TypeName.Name -eq 'ValidateSet' }
    if ($SetAttribute) {
        if (!(($SetAttribute.PositionalArguments | Select-Object -ExpandProperty Value) -contains $Value)) { Return $false }
    }
    $LengthAttribute = $paramast.Attributes | Where-Object { $_.TypeName.Name -eq 'ValidateLength' }
    if ($LengthAttribute) {
        if ($value.Length -lt $LengthAttribute.PositionalArguments[0].Value -or $value.Length -gt $LengthAttribute.PositionalArguments[1].Value) {
            Return $false
        }
    }
    $PatternAttribute = $paramast.Attributes | Where-Object { $_.TypeName.Name -eq 'ValidatePattern' }
    if ($PatternAttribute) {
        if ($Value -notmatch $PatternAttribute.PositionalArguments[0].Value) {
            Return $false
        }
    }
    $ScriptAttribute = $paramast.Attributes | Where-Object { $_.TypeName.Name -eq 'ValidateScript' }
    if ($ScriptAttribute) {
        $scriptBlock = [Scriptblock]::Create($ScriptAttribute.PositionalArguments[0].ScriptBlock.GetScriptBlock().ToString().Replace('$_','$Value'))
        Return $scriptBlock.Invoke()
    }

    Return $true
}

<#
.SYNOPSIS
    Gets a known folder's path using SHGetKnownFolderPath.
.PARAMETER Folder
    The known folder whose path to set.
#>

# USAGE: # Get-KnownFolderPath -KnownFolder 'Desktop'
# FROM: http://stackoverflow.com/questions/25709398/set-location-of-special-folders-with-powershell
# HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
function Get-KnownFolderPath {
    Param (
        [Parameter(Mandatory = $true)]
        [ValidateSet('AddNewPrograms', 'AdminTools', 'AppUpdates', 'CDBurning', 'ChangeRemovePrograms', 'CommonAdminTools', 'CommonOEMLinks', 'CommonPrograms', 'CommonStartMenu', 'CommonStartup', 'CommonTemplates', 'ComputerFolder', 'ConflictFolder', 'ConnectionsFolder', 'Contacts', 'ControlPanelFolder', 'Cookies', 'Desktop', 'Documents', 'Downloads', 'Favorites', 'Fonts', 'Games', 'GameTasks', 'History', 'InternetCache', 'InternetFolder', 'Links', 'LocalAppData', 'LocalAppDataLow', 'LocalizedResourcesDir', 'Music', 'NetHood', 'NetworkFolder', 'OriginalImages', 'PhotoAlbums', 'Pictures', 'Playlists', 'PrintersFolder', 'PrintHood', 'Profile', 'ProgramData', 'ProgramFiles', 'ProgramFilesX64', 'ProgramFilesX86', 'ProgramFilesCommon', 'ProgramFilesCommonX64', 'ProgramFilesCommonX86', 'Programs', 'Public', 'PublicDesktop', 'PublicDocuments', 'PublicDownloads', 'PublicGameTasks', 'PublicMusic', 'PublicPictures', 'PublicVideos', 'QuickLaunch', 'Recent', 'RecycleBinFolder', 'ResourceDir', 'RoamingAppData', 'SampleMusic', 'SamplePictures', 'SamplePlaylists', 'SampleVideos', 'SavedGames', 'SavedSearches', 'SEARCH_CSC', 'SEARCH_MAPI', 'SearchHome', 'SendTo', 'SidebarDefaultParts', 'SidebarParts', 'StartMenu', 'Startup', 'SyncManagerFolder', 'SyncResultsFolder', 'SyncSetupFolder', 'System', 'SystemX86', 'Templates', 'TreeProperties', 'UserProfiles', 'UsersFiles', 'Videos', 'Windows')]
        [string]$KnownFolder
    )

    # Define known folder GUIDs
    $KnownFolders = @{
        'AddNewPrograms'        = 'de61d971-5ebc-4f02-a3a9-6c82895e5c04';
        'AdminTools'            = '724EF170-A42D-4FEF-9F26-B60E846FBA4F';
        'AppUpdates'            = 'a305ce99-f527-492b-8b1a-7e76fa98d6e4';
        'CDBurning'             = '9E52AB10-F80D-49DF-ACB8-4330F5687855';
        'ChangeRemovePrograms'  = 'df7266ac-9274-4867-8d55-3bd661de872d';
        'CommonAdminTools'      = 'D0384E7D-BAC3-4797-8F14-CBA229B392B5';
        'CommonOEMLinks'        = 'C1BAE2D0-10DF-4334-BEDD-7AA20B227A9D';
        'CommonPrograms'        = '0139D44E-6AFE-49F2-8690-3DAFCAE6FFB8';
        'CommonStartMenu'       = 'A4115719-D62E-491D-AA7C-E74B8BE3B067';
        'CommonStartup'         = '82A5EA35-D9CD-47C5-9629-E15D2F714E6E';
        'CommonTemplates'       = 'B94237E7-57AC-4347-9151-B08C6C32D1F7';
        'ComputerFolder'        = '0AC0837C-BBF8-452A-850D-79D08E667CA7';
        'ConflictFolder'        = '4bfefb45-347d-4006-a5be-ac0cb0567192';
        'ConnectionsFolder'     = '6F0CD92B-2E97-45D1-88FF-B0D186B8DEDD';
        'Contacts'              = '56784854-C6CB-462b-8169-88E350ACB882';
        'ControlPanelFolder'    = '82A74AEB-AEB4-465C-A014-D097EE346D63';
        'Cookies'               = '2B0F765D-C0E9-4171-908E-08A611B84FF6';
        'Desktop'               = 'B4BFCC3A-DB2C-424C-B029-7FE99A87C641';
        'Documents'             = 'FDD39AD0-238F-46AF-ADB4-6C85480369C7';
        'Downloads'             = '374DE290-123F-4565-9164-39C4925E467B';
        'Favorites'             = '1777F761-68AD-4D8A-87BD-30B759FA33DD';
        'Fonts'                 = 'FD228CB7-AE11-4AE3-864C-16F3910AB8FE';
        'Games'                 = 'CAC52C1A-B53D-4edc-92D7-6B2E8AC19434';
        'GameTasks'             = '054FAE61-4DD8-4787-80B6-090220C4B700';
        'History'               = 'D9DC8A3B-B784-432E-A781-5A1130A75963';
        'InternetCache'         = '352481E8-33BE-4251-BA85-6007CAEDCF9D';
        'InternetFolder'        = '4D9F7874-4E0C-4904-967B-40B0D20C3E4B';
        'Links'                 = 'bfb9d5e0-c6a9-404c-b2b2-ae6db6af4968';
        'LocalAppData'          = 'F1B32785-6FBA-4FCF-9D55-7B8E7F157091';
        'LocalAppDataLow'       = 'A520A1A4-1780-4FF6-BD18-167343C5AF16';
        'LocalizedResourcesDir' = '2A00375E-224C-49DE-B8D1-440DF7EF3DDC';
        'Music'                 = '4BD8D571-6D19-48D3-BE97-422220080E43';
        'NetHood'               = 'C5ABBF53-E17F-4121-8900-86626FC2C973';
        'NetworkFolder'         = 'D20BEEC4-5CA8-4905-AE3B-BF251EA09B53';
        'OriginalImages'        = '2C36C0AA-5812-4b87-BFD0-4CD0DFB19B39';
        'PhotoAlbums'           = '69D2CF90-FC33-4FB7-9A0C-EBB0F0FCB43C';
        'Pictures'              = '33E28130-4E1E-4676-835A-98395C3BC3BB';
        'Playlists'             = 'DE92C1C7-837F-4F69-A3BB-86E631204A23';
        'PrintersFolder'        = '76FC4E2D-D6AD-4519-A663-37BD56068185';
        'PrintHood'             = '9274BD8D-CFD1-41C3-B35E-B13F55A758F4';
        'Profile'               = '5E6C858F-0E22-4760-9AFE-EA3317B67173';
        'ProgramData'           = '62AB5D82-FDC1-4DC3-A9DD-070D1D495D97';
        'ProgramFiles'          = '905e63b6-c1bf-494e-b29c-65b732d3d21a';
        'ProgramFilesX64'       = '6D809377-6AF0-444b-8957-A3773F02200E';
        'ProgramFilesX86'       = '7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E';
        'ProgramFilesCommon'    = 'F7F1ED05-9F6D-47A2-AAAE-29D317C6F066';
        'ProgramFilesCommonX64' = '6365D5A7-0F0D-45E5-87F6-0DA56B6A4F7D';
        'ProgramFilesCommonX86' = 'DE974D24-D9C6-4D3E-BF91-F4455120B917';
        'Programs'              = 'A77F5D77-2E2B-44C3-A6A2-ABA601054A51';
        'Public'                = 'DFDF76A2-C82A-4D63-906A-5644AC457385';
        'PublicDesktop'         = 'C4AA340D-F20F-4863-AFEF-F87EF2E6BA25';
        'PublicDocuments'       = 'ED4824AF-DCE4-45A8-81E2-FC7965083634';
        'PublicDownloads'       = '3D644C9B-1FB8-4f30-9B45-F670235F79C0';
        'PublicGameTasks'       = 'DEBF2536-E1A8-4c59-B6A2-414586476AEA';
        'PublicMusic'           = '3214FAB5-9757-4298-BB61-92A9DEAA44FF';
        'PublicPictures'        = 'B6EBFB86-6907-413C-9AF7-4FC2ABF07CC5';
        'PublicVideos'          = '2400183A-6185-49FB-A2D8-4A392A602BA3';
        'QuickLaunch'           = '52a4f021-7b75-48a9-9f6b-4b87a210bc8f';
        'Recent'                = 'AE50C081-EBD2-438A-8655-8A092E34987A';
        'RecycleBinFolder'      = 'B7534046-3ECB-4C18-BE4E-64CD4CB7D6AC';
        'ResourceDir'           = '8AD10C31-2ADB-4296-A8F7-E4701232C972';
        'RoamingAppData'        = '3EB685DB-65F9-4CF6-A03A-E3EF65729F3D';
        'SampleMusic'           = 'B250C668-F57D-4EE1-A63C-290EE7D1AA1F';
        'SamplePictures'        = 'C4900540-2379-4C75-844B-64E6FAF8716B';
        'SamplePlaylists'       = '15CA69B3-30EE-49C1-ACE1-6B5EC372AFB5';
        'SampleVideos'          = '859EAD94-2E85-48AD-A71A-0969CB56A6CD';
        'SavedGames'            = '4C5C32FF-BB9D-43b0-B5B4-2D72E54EAAA4';
        'SavedSearches'         = '7d1d3a04-debb-4115-95cf-2f29da2920da';
        'SEARCH_CSC'            = 'ee32e446-31ca-4aba-814f-a5ebd2fd6d5e';
        'SEARCH_MAPI'           = '98ec0e18-2098-4d44-8644-66979315a281';
        'SearchHome'            = '190337d1-b8ca-4121-a639-6d472d16972a';
        'SendTo'                = '8983036C-27C0-404B-8F08-102D10DCFD74';
        'SidebarDefaultParts'   = '7B396E54-9EC5-4300-BE0A-2482EBAE1A26';
        'SidebarParts'          = 'A75D362E-50FC-4fb7-AC2C-A8BEAA314493';
        'StartMenu'             = '625B53C3-AB48-4EC1-BA1F-A1EF4146FC19';
        'Startup'               = 'B97D20BB-F46A-4C97-BA10-5E3608430854';
        'SyncManagerFolder'     = '43668BF8-C14E-49B2-97C9-747784D784B7';
        'SyncResultsFolder'     = '289a9a43-be44-4057-a41b-587a76d7e7f9';
        'SyncSetupFolder'       = '0F214138-B1D3-4a90-BBA9-27CBC0C5389A';
        'System'                = '1AC14E77-02E7-4E5D-B744-2EB1AE5198B7';
        'SystemX86'             = 'D65231B0-B2F1-4857-A4CE-A8E7C6EA7D27';
        'Templates'             = 'A63293E8-664E-48DB-A079-DF759E0509F7';
        'TreeProperties'        = '5b3749ad-b49f-49c1-83eb-15370fbd4882';
        'UserProfiles'          = '0762D272-C50A-4BB0-A382-697DCD729B80';
        'UsersFiles'            = 'f3ce0f7c-4901-4acc-8648-d5d44b04ef8f';
        'Videos'                = '18989B1D-99B5-455B-841C-AB7C74E4DDFC';
        'Windows'               = 'F38BF404-1D43-42F2-9305-67DE0B28FC23';
    }
    $GetSignature = @'
    [DllImport("shell32.dll", CharSet = CharSet.Unicode)]public extern static int SHGetKnownFolderPath(
    ref Guid folderId,
    uint flags,
    IntPtr token,
    out IntPtr pszProfilePath);
'@

    $GetType = Add-Type -MemberDefinition $GetSignature -Name 'GetKnownFolders' -Namespace 'SHGetKnownFolderPath' -Using "System.Text" -PassThru
    $ptr = [intptr]::Zero
    [void]$GetType::SHGetKnownFolderPath([ref]$KnownFolders[$KnownFolder], 0, 0, [ref]$ptr)
    [System.Runtime.InteropServices.Marshal]::PtrToStringUni($ptr)
    [System.Runtime.InteropServices.Marshal]::FreeCoTaskMem($ptr)
}
<#
.SYNOPSIS
    Sets a known folder's path using SHSetKnownFolderPath.
.PARAMETER Folder
    The known folder whose path to set.
.PARAMETER Path
    The path.
#>

# USAGE: # Set-KnownFolderPath -KnownFolder 'Desktop' -Path '\\netserver\desktop\username\desktop'
# FROM: http://stackoverflow.com/questions/25709398/set-location-of-special-folders-with-powershell
# HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
function Set-KnownFolderPath {
    Param (
            [Parameter(Mandatory = $true)]
            [ValidateSet('AddNewPrograms', 'AdminTools', 'AppUpdates', 'CDBurning', 'ChangeRemovePrograms', 'CommonAdminTools', 'CommonOEMLinks', 'CommonPrograms', 'CommonStartMenu', 'CommonStartup', 'CommonTemplates', 'ComputerFolder', 'ConflictFolder', 'ConnectionsFolder', 'Contacts', 'ControlPanelFolder', 'Cookies', 'Desktop', 'Documents', 'Downloads', 'Favorites', 'Fonts', 'Games', 'GameTasks', 'History', 'InternetCache', 'InternetFolder', 'Links', 'LocalAppData', 'LocalAppDataLow', 'LocalizedResourcesDir', 'Music', 'NetHood', 'NetworkFolder', 'OriginalImages', 'PhotoAlbums', 'Pictures', 'Playlists', 'PrintersFolder', 'PrintHood', 'Profile', 'ProgramData', 'ProgramFiles', 'ProgramFilesX64', 'ProgramFilesX86', 'ProgramFilesCommon', 'ProgramFilesCommonX64', 'ProgramFilesCommonX86', 'Programs', 'Public', 'PublicDesktop', 'PublicDocuments', 'PublicDownloads', 'PublicGameTasks', 'PublicMusic', 'PublicPictures', 'PublicVideos', 'QuickLaunch', 'Recent', 'RecycleBinFolder', 'ResourceDir', 'RoamingAppData', 'SampleMusic', 'SamplePictures', 'SamplePlaylists', 'SampleVideos', 'SavedGames', 'SavedSearches', 'SEARCH_CSC', 'SEARCH_MAPI', 'SearchHome', 'SendTo', 'SidebarDefaultParts', 'SidebarParts', 'StartMenu', 'Startup', 'SyncManagerFolder', 'SyncResultsFolder', 'SyncSetupFolder', 'System', 'SystemX86', 'Templates', 'TreeProperties', 'UserProfiles', 'UsersFiles', 'Videos', 'Windows')]
            [string]$KnownFolder,

            [Parameter(Mandatory = $true)]
            [string]$Path
    )

    # Define known folder GUIDs
    $KnownFolders = @{
        'AddNewPrograms' = 'de61d971-5ebc-4f02-a3a9-6c82895e5c04';
        'AdminTools' = '724EF170-A42D-4FEF-9F26-B60E846FBA4F';
        'AppUpdates' = 'a305ce99-f527-492b-8b1a-7e76fa98d6e4';
        'CDBurning' = '9E52AB10-F80D-49DF-ACB8-4330F5687855';
        'ChangeRemovePrograms' = 'df7266ac-9274-4867-8d55-3bd661de872d';
        'CommonAdminTools' = 'D0384E7D-BAC3-4797-8F14-CBA229B392B5';
        'CommonOEMLinks' = 'C1BAE2D0-10DF-4334-BEDD-7AA20B227A9D';
        'CommonPrograms' = '0139D44E-6AFE-49F2-8690-3DAFCAE6FFB8';
        'CommonStartMenu' = 'A4115719-D62E-491D-AA7C-E74B8BE3B067';
        'CommonStartup' = '82A5EA35-D9CD-47C5-9629-E15D2F714E6E';
        'CommonTemplates' = 'B94237E7-57AC-4347-9151-B08C6C32D1F7';
        'ComputerFolder' = '0AC0837C-BBF8-452A-850D-79D08E667CA7';
        'ConflictFolder' = '4bfefb45-347d-4006-a5be-ac0cb0567192';
        'ConnectionsFolder' = '6F0CD92B-2E97-45D1-88FF-B0D186B8DEDD';
        'Contacts' = '56784854-C6CB-462b-8169-88E350ACB882';
        'ControlPanelFolder' = '82A74AEB-AEB4-465C-A014-D097EE346D63';
        'Cookies' = '2B0F765D-C0E9-4171-908E-08A611B84FF6';
        'Desktop' = 'B4BFCC3A-DB2C-424C-B029-7FE99A87C641';
        'Documents' = 'FDD39AD0-238F-46AF-ADB4-6C85480369C7';
        'Downloads' = '374DE290-123F-4565-9164-39C4925E467B';
        'Favorites' = '1777F761-68AD-4D8A-87BD-30B759FA33DD';
        'Fonts' = 'FD228CB7-AE11-4AE3-864C-16F3910AB8FE';
        'Games' = 'CAC52C1A-B53D-4edc-92D7-6B2E8AC19434';
        'GameTasks' = '054FAE61-4DD8-4787-80B6-090220C4B700';
        'History' = 'D9DC8A3B-B784-432E-A781-5A1130A75963';
        'InternetCache' = '352481E8-33BE-4251-BA85-6007CAEDCF9D';
        'InternetFolder' = '4D9F7874-4E0C-4904-967B-40B0D20C3E4B';
        'Links' = 'bfb9d5e0-c6a9-404c-b2b2-ae6db6af4968';
        'LocalAppData' = 'F1B32785-6FBA-4FCF-9D55-7B8E7F157091';
        'LocalAppDataLow' = 'A520A1A4-1780-4FF6-BD18-167343C5AF16';
        'LocalizedResourcesDir' = '2A00375E-224C-49DE-B8D1-440DF7EF3DDC';
        'Music' = '4BD8D571-6D19-48D3-BE97-422220080E43';
        'NetHood' = 'C5ABBF53-E17F-4121-8900-86626FC2C973';
        'NetworkFolder' = 'D20BEEC4-5CA8-4905-AE3B-BF251EA09B53';
        'OriginalImages' = '2C36C0AA-5812-4b87-BFD0-4CD0DFB19B39';
        'PhotoAlbums' = '69D2CF90-FC33-4FB7-9A0C-EBB0F0FCB43C';
        'Pictures' = '33E28130-4E1E-4676-835A-98395C3BC3BB';
        'Playlists' = 'DE92C1C7-837F-4F69-A3BB-86E631204A23';
        'PrintersFolder' = '76FC4E2D-D6AD-4519-A663-37BD56068185';
        'PrintHood' = '9274BD8D-CFD1-41C3-B35E-B13F55A758F4';
        'Profile' = '5E6C858F-0E22-4760-9AFE-EA3317B67173';
        'ProgramData' = '62AB5D82-FDC1-4DC3-A9DD-070D1D495D97';
        'ProgramFiles' = '905e63b6-c1bf-494e-b29c-65b732d3d21a';
        'ProgramFilesX64' = '6D809377-6AF0-444b-8957-A3773F02200E';
        'ProgramFilesX86' = '7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E';
        'ProgramFilesCommon' = 'F7F1ED05-9F6D-47A2-AAAE-29D317C6F066';
        'ProgramFilesCommonX64' = '6365D5A7-0F0D-45E5-87F6-0DA56B6A4F7D';
        'ProgramFilesCommonX86' = 'DE974D24-D9C6-4D3E-BF91-F4455120B917';
        'Programs' = 'A77F5D77-2E2B-44C3-A6A2-ABA601054A51';
        'Public' = 'DFDF76A2-C82A-4D63-906A-5644AC457385';
        'PublicDesktop' = 'C4AA340D-F20F-4863-AFEF-F87EF2E6BA25';
        'PublicDocuments' = 'ED4824AF-DCE4-45A8-81E2-FC7965083634';
        'PublicDownloads' = '3D644C9B-1FB8-4f30-9B45-F670235F79C0';
        'PublicGameTasks' = 'DEBF2536-E1A8-4c59-B6A2-414586476AEA';
        'PublicMusic' = '3214FAB5-9757-4298-BB61-92A9DEAA44FF';
        'PublicPictures' = 'B6EBFB86-6907-413C-9AF7-4FC2ABF07CC5';
        'PublicVideos' = '2400183A-6185-49FB-A2D8-4A392A602BA3';
        'QuickLaunch' = '52a4f021-7b75-48a9-9f6b-4b87a210bc8f';
        'Recent' = 'AE50C081-EBD2-438A-8655-8A092E34987A';
        'RecycleBinFolder' = 'B7534046-3ECB-4C18-BE4E-64CD4CB7D6AC';
        'ResourceDir' = '8AD10C31-2ADB-4296-A8F7-E4701232C972';
        'RoamingAppData' = '3EB685DB-65F9-4CF6-A03A-E3EF65729F3D';
        'SampleMusic' = 'B250C668-F57D-4EE1-A63C-290EE7D1AA1F';
        'SamplePictures' = 'C4900540-2379-4C75-844B-64E6FAF8716B';
        'SamplePlaylists' = '15CA69B3-30EE-49C1-ACE1-6B5EC372AFB5';
        'SampleVideos' = '859EAD94-2E85-48AD-A71A-0969CB56A6CD';
        'SavedGames' = '4C5C32FF-BB9D-43b0-B5B4-2D72E54EAAA4';
        'SavedSearches' = '7d1d3a04-debb-4115-95cf-2f29da2920da';
        'SEARCH_CSC' = 'ee32e446-31ca-4aba-814f-a5ebd2fd6d5e';
        'SEARCH_MAPI' = '98ec0e18-2098-4d44-8644-66979315a281';
        'SearchHome' = '190337d1-b8ca-4121-a639-6d472d16972a';
        'SendTo' = '8983036C-27C0-404B-8F08-102D10DCFD74';
        'SidebarDefaultParts' = '7B396E54-9EC5-4300-BE0A-2482EBAE1A26';
        'SidebarParts' = 'A75D362E-50FC-4fb7-AC2C-A8BEAA314493';
        'StartMenu' = '625B53C3-AB48-4EC1-BA1F-A1EF4146FC19';
        'Startup' = 'B97D20BB-F46A-4C97-BA10-5E3608430854';
        'SyncManagerFolder' = '43668BF8-C14E-49B2-97C9-747784D784B7';
        'SyncResultsFolder' = '289a9a43-be44-4057-a41b-587a76d7e7f9';
        'SyncSetupFolder' = '0F214138-B1D3-4a90-BBA9-27CBC0C5389A';
        'System' = '1AC14E77-02E7-4E5D-B744-2EB1AE5198B7';
        'SystemX86' = 'D65231B0-B2F1-4857-A4CE-A8E7C6EA7D27';
        'Templates' = 'A63293E8-664E-48DB-A079-DF759E0509F7';
        'TreeProperties' = '5b3749ad-b49f-49c1-83eb-15370fbd4882';
        'UserProfiles' = '0762D272-C50A-4BB0-A382-697DCD729B80';
        'UsersFiles' = 'f3ce0f7c-4901-4acc-8648-d5d44b04ef8f';
        'Videos' = '18989B1D-99B5-455B-841C-AB7C74E4DDFC';
        'Windows' = 'F38BF404-1D43-42F2-9305-67DE0B28FC23';
    }

    # Define SHSetKnownFolderPath if it hasn't been defined already
    $Type = ([System.Management.Automation.PSTypeName]'KnownFolders').Type
    if (-not $Type) {
        $Signature = @'
[DllImport("shell32.dll")]
public extern static int SHSetKnownFolderPath(ref Guid folderId, uint flags, IntPtr token, [MarshalAs(UnmanagedType.LPWStr)] string path);
'@

        $Type = Add-Type -MemberDefinition $Signature -Name 'KnownFolders' -Namespace 'SHSetKnownFolderPath' -PassThru
    }

    # Validate the path
    if (Test-Path $Path -PathType Container) {
        # Call SHSetKnownFolderPath
        return $Type::SHSetKnownFolderPath([ref]$KnownFolders[$KnownFolder], 0, 0, $Path)
    } else {
        throw New-Object System.IO.DirectoryNotFoundException "Could not find part of the path $Path."
    }
}
function Test-IsNonInteractiveShell {
    if ([Environment]::UserInteractive -and ($env:TERM_PROGRAM -ne 'vscode') ) {
        foreach ($arg in [Environment]::GetCommandLineArgs()) {
            # Test each Arg for match of abbreviated '-NonInteractive' command.
            if ($arg -like '-NonI*') {
                return $true
            }
        }
    }
    return $false
}

if($env:TERM_PROGRAM -eq 'vscode') {
    # do some stuff...
  }
function Test-ParameterValidation {
    [CmdletBinding()]
    [OutputType([bool])]
    param (
        [System.Management.Automation.ParameterMetadata]$Param,
        [System.Object]$Value
    )
    [System.Management.Automation.ValidateSetAttribute]$SetAttribute = $Param.Attributes | Where-Object {$_.TypeId -eq [System.Management.Automation.ValidateSetAttribute]}
    if ($SetAttribute){
        if (!($SetAttribute.ValidValues -contains $Value)){Return $false}
    }
    $LengthAttribute = $Param.Attributes | Where-Object {$_.TypeId -eq [System.Management.Automation.ValidateLengthAttribute]}
    if ($LengthAttribute){
        if ($value.ToString().Length -lt $LengthAttribute.MinLength -or $value.ToString().Length -gt $LengthAttribute.MaxLength){
            Return $false
        }
    }
    $PatternAttribute = $Param.Attributes | Where-Object {$_.TypeId -eq [System.Management.Automation.ValidatePatternAttribute]}
    if ($PatternAttribute){
        if ($Value -notmatch $PatternAttribute.RegexPattern){
            Return $false
        }
    }
    [System.Management.Automation.ValidateScriptAttribute]$ScriptAttribute = $Param.Attributes | Where-Object {$_.TypeId -eq [System.Management.Automation.ValidateScriptAttribute]}
    if ($ScriptAttribute){
        Return (Invoke-Expression $ScriptAttribute.ScriptBlock.ToString().Replace('$_', '$Value'))
    }

    Return $true
}
#Adapted from https://gist.github.com/altrive/5329377
#Based on <http://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542>
#Adapted to use CIM based on https://www.reddit.com/r/SCCM/comments/b3r7n4/can_you_change_the_pending_reboot_time_on_a_sccm/
function Test-PendingReboot {
    if (Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending" -EA Ignore) { return $true }
    if (Get-Item "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired" -EA Ignore) { return $true }
    if (Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager" -Name PendingFileRenameOperations -EA Ignore) { return $true }
    if (Invoke-CimMethod -Namespace root/ccm/ClientSDK -ClassName CCM_ClientUtilities -MethodName DetermineIfRebootPending -ea silentlycontinu) { return $true }
    return $false
}