All posts by steven

Create Tax report of OrangeHRM with Powershell

This code is only usefull if there is only one employee.

Export four seperate CSV files out of the database of OrangeHRM. The tables you should export are the following:

ohrm_customer
ohrm_project
ohrm_project_acitivity
ohrm_timesheet_item

You should use the following settings for the export ni PHPMyAdmin:

OrangeHRM

Export each table with the following names:

ohrm_customer                  – Customers.csv
ohrm_project                       – Projects.csv
ohrm_project_acitivity   – Activities.csv
ohrm_timesheet_item     – Items.csv

Place the CSV files and the script below in the same directory.

$Activities = import-csv ".\Activities.csv" -Delimiter ";"
$Customers = import-csv ".\Customers.csv" -Delimiter ";"
$Items = import-csv ".\Items.csv" -Delimiter ";"
$Projects = import-csv ".\Projects.csv" -Delimiter ";"
$Export = @()
Foreach ($item in $Projects){[int]$count = $item.customer_id
$count--
$item.customer_id = $Customers[$count].name
}
Foreach ($item in $items){
[int]$count = $item.Activity_id
$count--
$item.Activity_id = $Activities[$count].name

[int]$count = $item.project_id
$count--
$item.Employee_id = $Projects[$count].customer_id
[int]$count = $item.project_id
$count--
$item.project_id = $Projects[$count].name
}
$items | Export-CSV -path ".\Export.csv" -Delimiter ";"

This will export a CSV file in the same directory. The only thing you have to do now is replace the header of employee_id to something more meaningful. In fact you will probably have to replace all the headers to something a bit more meaning full.

 

Use .htaccess to redirect to https

If you need to redirect any request in a site to https you can use mod rewrite in a htaccess file. In this specific case we want to redirect whatever insecure url is used to a secure url. The advantage is that it doesn’t do a thing in the request was already secure. Also if you have multiple headers pointing to that directory, the htaccess file will redirect them preserving the original host header use the code below.

RewriteEngine On
 RewriteCond %{HTTPS} off
 RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Using filters to find groups with mail address

You can export a list of all groups with the field mail enabled by running the following code:

$list = Get-ADGroup -Filter * -Properties * | Where {$_.mail -ne $null -and $_.GroupScope -match "Global"}
$list | export-csv -Path Globalmetmail.csv -Delimiter ";"

To find groups inside a certain OU for example if you have a distribution OU you may want to export certain Grouptypes:

$list2 = Get-ADGroup -Filter * -Properties * | Where {$_.CanonicalName -match "Distribution" -and $_.GroupScope -match "Global"}
$list2 |export-csv -Path GlobalEnInDistributionOU.csv -Delimiter ";"

 

 

SHA2 certificate OpenSSL Windows

If you have Windows and an OpenSSL installation you can request a SHA256 certificate using the followin code:

set domein=YourDomain
set pass=YourPassword
set organisatie=YourOrganisation
set provincie=YourProviceorState
set stad=YourCity
set string="/CN=%domein%/O=%organisatie%/C=NL/ST=%provincie%/L=%stad%"
echo %string%
openssl genrsa -des3 -passout pass:%pass% 2048 > %domein%.key
openssl rsa -in %domein%.key -passin pass:%pass% -out %domein%-decrypted.key
openssl req –sha256 -new -key %domein%-decrypted.key -subj %string% -out %domein%.csr

SHA2 certificate OpenSSL Linux

To generate a certificate signing request with requesting a SHA256 signed certificate you can run the following script on a linux box with OpenSSL installed on it. Run this Shell script. chmod +X of course

 

domein=YourFQDN
pass=YourPassword
organisatie=YourOrganisation
provincie=YourProvince
stad=YourCity

string=/CN=$domein/O=$organisatie/C=NL/ST=$provincie/L=$stad
openssl genrsa -des3 -passout pass:$pass 2048 > $domein.key
openssl req -sha256 -new -key $domein.key -passin pass:$pass -subj $string -out $domein.csr
openssl rsa -in $domein.key -passin pass:$pass -out $domein-decrypted.key

~

This script will output a private key, a decrypted private key and a CSR.

If you received the CA’s response and it is in a wrong format you can run all of the lines below. If you received a PEM formatted response you can just the line with PKCS12 OpenSSL command.

 

domein=YourFQDN
pass=YourPassword

openssl x509 -in $domein.cer  -out $domein.der -outform DER
openssl x509 -in $domein.der -inform DER -out $domein.pem -outform PEM
openssl pkcs12 -export -in $domein.pem -inkey $domein.key -passin pass:$pass -out $domein.pfx -passout pass:$pass -name $domein

Set time om ESXi host in Command Line

As you will probably know, ESXi does not support Time Zones for whatever reasons. Sometimes however Windows takes over the system time of de ESXi host. If you configured NTP services well enough this shouldn’t cause any problems. If you didn’t you need to configure the time manually. You can of course also need this for just checking of the time is right.

Check the time:

esxcli system time get

Set the time:

esxcli system time set -d 28 -M 4 -y 2014 -H 10 -m 0 -s 0

Please bare in mind that ESXi does not support timezones so you should configure the time for the timezone for UTC. Also keep in mind that if you configured ESXi to check the NTP from now and then that the time will be off again. The best thing to do is to configure the NTP infrastructure in Windows.

Encrypt values using AES RSA in Powershell

You can encrypt a password so that only under your account it can be decrypted. If however you need some other user to decrypt the data the code is worthless. You can use different code for this case. You need a certificate with private key. It can be a certificate that is self signed. You can use byte values of a maximum van 32 (equals 256 bit). I would recommend using a 32 Byte value. Get the thumbprint value using the following code:

Get-Item -Path Cert:\CurrentUser\My\*

Of course you can also use a certificate that is installed on the local machine. For the sake of better security I would use a certificate that is installed in the CurrentUser part of the certificate store.

If you know the thumbprint of the certificate, state that value in the $thumbprint string. Enter the plaintext value which you want to encrypt in the string $Securestring. Configure the Export-Clixml path to you liking. You can change the name of the XML file without voiding the abillity to decrypt.

try
{
    $secureString = 'StrongPassword' | 
                    ConvertTo-SecureString -AsPlainText -Force

    # Generate our new 32-byte AES key.  I don't recommend using Get-Random for this; the System.Security.Cryptography namespace
    # offers a much more secure random number generator.

    $key = New-Object byte[](32)
    $rng = [System.Security.Cryptography.RNGCryptoServiceProvider]::Create()

    $rng.GetBytes($key)

    $encryptedString = ConvertFrom-SecureString -SecureString $secureString -Key $key

    # This is the thumbprint of a certificate on my test system where I have the private key installed.Note that the thumbprint value is CASE SENSITIVE

    $thumbprint = 'D180EA99616A925E716278635E29159BC7105663'
    $cert = Get-Item -Path Cert:\CurrentUser\My\$thumbprint -ErrorAction Stop

    $encryptedKey = $cert.PublicKey.Key.Encrypt($key, $true)

    $object = New-Object psobject -Property @{
        Key = $encryptedKey
        Payload = $encryptedString
    }

    $object | Export-Clixml .\encryptionTest2.xml

}
finally
{
    if ($null -ne $key) { [array]::Clear($key, 0, $key.Length) }

You can decrypt the value securely using the following code:

try
{
    $object = Import-Clixml -Path .\encryptionTest2.xml

    $thumbprint = 'D180EA99616A925E716278635E29159BC7105663'
    $cert = Get-Item -Path Cert:\CurrentUser\My\$thumbprint -ErrorAction Stop

    $key = $cert.PrivateKey.Decrypt($object.Key, $true)

    $secureString = $object.Payload | ConvertTo-SecureString -Key $key 
	
}
finally
{
    if ($null -ne $key) { [array]::Clear($key, 0, $key.Length) }
}

$cred = New-Object System.Management.Automation.PSCredential(Useraccount, $secureString)

Now you can run command’s under an account without having to compromise the password easily. You need to have the certificate to decrypt.  Don’t try to encrypt the username also. Powershell does not accept secure usernames somehow.  An example of how to use this would be:

Import-Module ActiveDirectory
$Username = [Environment]::UserName
Get-ADUser -Identity $Username -Credential $Cred

To troubleshoot you can decrypt the password in plain text using the following code. Please note that this leaves the unencrypted password in the memory waiting to be exploited.

$cred = New-Object System.Management.Automation.PSCredential('Username', $secureString)
$plainText = $cred.GetNetworkCredential().Password
Write-Host $Plaintext

Encrypt Values using DPAPI

You can encrypt passwords for your account only using DPAPI. You need the function on this site.

Import the module. On some hardened systems using:

Import-Module '.\Modulename.psm1' -Force

Next encrypt the password using the following command:

$secureString = Read-Host -AsSecureString "Enter a secret password." 

# You can pass basically anything as the Entropy value, but I'd recommend sticking to simple value types (including strings),
# or arrays of those types, to make sure that the binary serialization of your entropy object doesn't change between
# script executions.  Here, we'll use Pi.  Edit:  The latest version of the code enforces the use of the recommended simple
# types, unless you also use the -Force switch.

$secureString | ConvertFrom-SecureString -Entropy ([Math]::PI) | Out-File .\storedPassword.txt

You can use it by decrypting the password as a secure string using the following code:

$newSecureString = Get-Content -Path .\storedPassword.txt | ConvertTo-SecureString -Entropy ([Math]::PI)

You can decrypt the password as plain text using the following code:

$newSecureString = Get-Content -Path .\storedPassword.txt | ConvertTo-SecureString -Entropy ([Math]::PI)
$newSecureString | ConvertFrom-SecureString -AsPlainText -Force

Function for securing passwords with DPAPI

DPAPI is a encryptionprofile that prevents any other process to access data. Only your user account can decrypt the data. Also only on the computer where you encrypted to password on. If you have a roaming profile you don’t have this issue. What administrator use a roaming profile!?

PSM1:

requires -Version 2.0

if ($PSVersionTable.PSVersion.Major -ge 3)
{
    Import-Module Microsoft.PowerShell.Security -Global
}

$script:validEntropyTypes = @(
    [System.ValueType]
    [string]
    [System.Security.SecureString]
    [System.Text.StringBuilder]
)

function ConvertTo-SecureString
{
    <#
    
    .ForwardHelpTargetName ConvertTo-SecureString
    .ForwardHelpCategory Cmdlet
    
    #>

    [CmdletBinding(DefaultParameterSetName='Secure')]
    param(
        [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
        [string]
        ${String},
    
        [Parameter(ParameterSetName='PlainText', Position=1)]
        [switch]
        ${AsPlainText},
    
        [Parameter(ParameterSetName='PlainText', Position=2)]
        [Parameter(ParameterSetName = 'WithEntropy')]
        [switch]
        ${Force},
    
        [Parameter(ParameterSetName='Secure', Position=1)]
        [System.Security.SecureString]
        ${SecureKey},
    
        [Parameter(ParameterSetName='Open')]
        [byte[]]
        ${Key},

        [Parameter(ParameterSetName = 'WithEntropy')]
        [Object]
        $Entropy
    )
    
    begin
    {
        Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState

        if ($PSCmdlet.ParameterSetName -eq 'WithEntropy')
        {
            try
            {
                $entropyBytes = Get-EntropyBytes -Entropy $Entropy -Force:$Force
            }
            catch
            {
                throw
            }
        }
    }

    process
    {
        switch ($PSCmdlet.ParameterSetName)
        {
            'WithEntropy'
            {
                Add-Type -AssemblyName 'System.Security' -ErrorAction Stop

                try
                {
                    $encryptedBytes = Get-ByteArrayFromString -String $String
                    $plainTextBytes = [System.Security.Cryptography.ProtectedData]::Unprotect($encryptedBytes, $entropyBytes, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)
                    $plainTextChars = [System.Text.Encoding]::Unicode.GetChars($plainTextBytes)

                    $secureString = New-Object System.Security.SecureString

                    foreach ($char in $plainTextChars)
                    {
                        $secureString.AppendChar($char)
                    }

                    $secureString.MakeReadOnly()

                    return $secureString
                }
                catch
                {
                    Write-Error -ErrorRecord $_
                }
                finally
                {
                    if ($null -ne $plainTextChars) { [array]::Clear($plainTextChars, 0, $plainTextChars.Count) }
                    if ($null -ne $plainTextBytes) { [array]::Clear($plainTextBytes, 0, $plainTextBytes.Count) }
                    if ($null -ne $entropyBytes)   { [array]::Clear($entropyBytes, 0, $entropyBytes.Count) }
                }
                
                break
            }

            default
            {
                try
                {
                    $cmd = Get-Command -Name ConvertTo-SecureString -CommandType Cmdlet
                    return & $cmd @PSBoundParameters
                }
                catch
                {
                    Write-Error -ErrorRecord $_
                }
                
                break
            }
        }

    } # process
    
} # function ConvertTo-SecureString

function ConvertFrom-SecureString
{
    <#
    
    .ForwardHelpTargetName ConvertFrom-SecureString
    .ForwardHelpCategory Cmdlet
    
    #>

    [CmdletBinding(DefaultParameterSetName='Secure')]
    param(
        [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
        [ValidateScript({ $_.Length -gt 0 })]
        [System.Security.SecureString]
        ${SecureString},
    
        [Parameter(ParameterSetName='Secure', Position=1)]
        [System.Security.SecureString]
        ${SecureKey},
    
        [Parameter(ParameterSetName='Open')]
        [byte[]]
        ${Key},

        [Parameter(ParameterSetName = 'WithEntropy')]
        [Object]
        $Entropy,

        [Parameter(ParameterSetName = 'PlainText')]
        [switch]
        $AsPlainText,

        [Parameter(ParameterSetName = 'PlainText')]
        [Parameter(ParameterSetName = 'WithEntropy')]
        [switch]
        $Force
    )
    
    begin
    {
        Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState

        if ($PSCmdlet.ParameterSetName -eq 'WithEntropy')
        {
            Add-Type -AssemblyName 'System.Security'

            try
            {
                $entropyBytes = Get-EntropyBytes -Entropy $Entropy -Force:$Force
            }
            catch
            {
                throw
            }
        }
        elseif ($PSCmdlet.ParameterSetName -eq 'PlainText' -and -not $Force)
        {
            throw 'The system cannot protect plain text output.  To suppress this warning and convert the SecureString to plain text, reissue the command specifying the Force parameter.'
        }
    }

    process
    {
        switch ($PSCmdlet.ParameterSetName)
        {
            'PlainText'
            {
                try
                {
                    $ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToGlobalAllocUnicode($secureString)
                    return [System.Runtime.InteropServices.Marshal]::PtrToStringUni($ptr)
                }
                catch
                {
                    Write-Error -ErrorRecord $_
                }
                finally
                {
                    if ($null -ne $ptr) { [System.Runtime.InteropServices.Marshal]::ZeroFreeGlobalAllocUnicode($ptr) }
                }
                
                break
            }

            'WithEntropy'
            {
                try
                {
                    $ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToGlobalAllocUnicode($secureString)
                    $chars = New-Object Char[]($secureString.Length)
                    [System.Runtime.InteropServices.Marshal]::Copy($ptr, $chars, 0, $secureString.Length)
                    $bytes = [System.Text.Encoding]::Unicode.GetBytes($chars)
                    $encryptedBytes = [System.Security.Cryptography.ProtectedData]::Protect($bytes, $entropyBytes, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)

                    return Get-StringFromByteArray -ByteArray $encryptedBytes
                }
                catch
                {
                    Write-Error -ErrorRecord $_
                }
                finally
                {
                    if ($null -ne $ptr)          { [System.Runtime.InteropServices.Marshal]::ZeroFreeGlobalAllocUnicode($ptr) }
                    if ($null -ne $chars)        { [array]::Clear($chars, 0, $chars.Count) }
                    if ($null -ne $bytes)        { [array]::Clear($bytes, 0, $bytes.Count) }
                    if ($null -ne $entropyBytes) { [array]::Clear($entropyBytes, 0, $entropyBytes.Count) }
                }
                
                break
            }

            default
            {
                try
                {
                    $cmd = Get-Command -Name ConvertFrom-SecureString -CommandType Cmdlet
                    return & $cmd @PSBoundParameters
                }
                catch
                {
                    Write-Error -ErrorRecord $_
                }
                
                break
            }
        }

    } # process

} # function ConvertTo-SecureString

function Get-ByteArrayFromString
{
    # Converts a string containing an even number of hexadecimal characters into a byte array.

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [ValidateScript({
            # Could use ValidatePattern for this, but ValidateScript allows for a more user-friendly error message.
            if ($_ -match '[^0-9A-F]')
            {
                throw 'String must only contain hexadecimal characters (0-9 and A-F).'
            }

            if ($_.Length % 2 -ne 0)
            {
                throw 'String must contain an even number of characters'
            }

            return $true
        })]
        [string]
        $String
    )

    $length = $String.Length / 2
    $bytes = New-Object byte[]($length)

    for ($i = 0; $i -lt $length; $i++)
    {
        $bytes[$i] = [byte]::Parse($String.Substring($i * 2, 2), [Globalization.NumberStyles]::AllowHexSpecifier, [Globalization.CultureInfo]::InvariantCulture)
    }

    return ,$bytes
}

function Get-EntropyBytes
{
    [CmdletBinding()]
    param (
        $Entropy,

        [switch]
        $Force
    )

    if ($null -eq $Entropy)
    {
        return $null
    }
    elseif (-not $Force -and -not (Test-EntropyType -Object $Entropy))
    {
        throw @'
Entropy object's type should be a value type, string, StringBuilder, SecureString, or an array containing only value types or strings.
Use of other object types might result in a different binary representation of the object between script executions.  To suppress this message and use any type of entropy object, use the -Force switch.
'@
    }

    if ($Entropy -is [byte[]])
    {
        # Clone the object because the caller may be zeroing out the byte array when they're done, due
        # to it potentially containing plain text data from a SecureString.

        return $Entropy.Clone()
    }
    elseif ($Entropy -is [string])
    {
        return [System.Text.Encoding]::Unicode.GetBytes($Entropy)
    }
    elseif ($Entropy -is [System.Text.StringBuilder])
    {
        return [System.Text.Encoding]::Unicode.GetBytes($Entropy.ToString())
    }
    elseif ($Entropy -is [System.Security.SecureString])
    {
        try
        {
            $ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToGlobalAllocUnicode($Entropy)
            $chars = New-Object Char[]($Entropy.Length)

            [System.Runtime.InteropServices.Marshal]::Copy($ptr, $chars, $Entropy.Length)

            return [System.Text.Encoding]::Unicode.GetBytes($chars)
        }
        catch
        {
            throw
        }
        finally
        {
            if ($null -ne $ptr) { [System.Runtime.InteropServices.Marshal]::ZeroFreeGlobalAllocUnicode($ptr) }
            if ($null -ne $chars) { [Array]::Clear($chars) }
        }
    }
    else
    {
        try
        {
            $ms = New-Object System.IO.MemoryStream
            $bf = New-Object System.Runtime.Serialization.Formatters.Binary.BinaryFormatter

            $bf.Serialize($ms, $Entropy)
            
            return ,$ms.ToArray()
        }
        catch
        {
            throw
        }
        finally
        {
            if ($null -ne $ms) { $ms.Dispose() }
        }
    }
}

function Get-StringFromByteArray
{
    # Converts byte array into a string of hexadecimal characters in the same order as the byte array

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [byte[]]
        $ByteArray
    )

    $sb = New-Object System.Text.StringBuilder

    for ($i = 0; $i -lt $ByteArray.Length; $i++)
    {
        $null = $sb.Append($ByteArray[$i].ToString('x2', [Globalization.CultureInfo]::InvariantCulture))
    }

    return $sb.ToString()
}

function Test-EntropyType
{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        $Object
    )

    if ($Object -is [array])
    {
        foreach ($obj in $Object)
        {
            if ($obj -isnot [System.ValueType] -and $obj -isnot [string])
            {
                return $false
            }
        }

        return $true
    }
    else
    {
        foreach ($type in $script:validEntropyTypes)
        {
            if ($Object -is $type)
            {
                return $true
            }
        }

        return $false
    }
}

function Get-CallerPreference
{
    <#
    .Synopsis
       Fetches "Preference" variable values from the caller's scope.
    .DESCRIPTION
       Script module functions do not automatically inherit their caller's variables, but they can be
       obtained through the $PSCmdlet variable in Advanced Functions.  This function is a helper function
       for any script module Advanced Function; by passing in the values of $ExecutionContext.SessionState
       and $PSCmdlet, Get-CallerPreference will set the caller's preference variables locally.
    .PARAMETER Cmdlet
       The $PSCmdlet object from a script module Advanced Function.
    .PARAMETER SessionState
       The $ExecutionContext.SessionState object from a script module Advanced Function.  This is how the
       Get-CallerPreference function sets variables in its callers' scope, even if that caller is in a different
       script module.
    .PARAMETER Name
       Optional array of parameter names to retrieve from the caller's scope.  Default is to retrieve all
       Preference variables as defined in the about_Preference_Variables help file (as of PowerShell 4.0)
       This parameter may also specify names of variables that are not in the about_Preference_Variables
       help file, and the function will retrieve and set those as well.
    .EXAMPLE
       Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState

       Imports the default PowerShell preference variables from the caller into the local scope.
    .EXAMPLE
       Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState -Name 'ErrorActionPreference','SomeOtherVariable'

       Imports only the ErrorActionPreference and SomeOtherVariable variables into the local scope.
    .EXAMPLE
       'ErrorActionPreference','SomeOtherVariable' | Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState

       Same as Example 2, but sends variable names to the Name parameter via pipeline input.
    .INPUTS
       String
    .OUTPUTS
       None.  This function does not produce pipeline output.
    .LINK
       about_Preference_Variables
    #>

    [CmdletBinding(DefaultParameterSetName = 'AllVariables')]
    param (
        [Parameter(Mandatory = $true)]
        [ValidateScript({ $_.GetType().FullName -eq 'System.Management.Automation.PSScriptCmdlet' })]
        $Cmdlet,

        [Parameter(Mandatory = $true)]
        [System.Management.Automation.SessionState]
        $SessionState,

        [Parameter(ParameterSetName = 'Filtered', ValueFromPipeline = $true)]
        [string[]]
        $Name
    )

    begin
    {
        $filterHash = @{}
    }
    
    process
    {
        if ($null -ne $Name)
        {
            foreach ($string in $Name)
            {
                $filterHash[$string] = $true
            }
        }
    }

    end
    {
        # List of preference variables taken from the about_Preference_Variables help file in PowerShell version 4.0

        $vars = @{
            'ErrorView' = $null
            'FormatEnumerationLimit' = $null
            'LogCommandHealthEvent' = $null
            'LogCommandLifecycleEvent' = $null
            'LogEngineHealthEvent' = $null
            'LogEngineLifecycleEvent' = $null
            'LogProviderHealthEvent' = $null
            'LogProviderLifecycleEvent' = $null
            'MaximumAliasCount' = $null
            'MaximumDriveCount' = $null
            'MaximumErrorCount' = $null
            'MaximumFunctionCount' = $null
            'MaximumHistoryCount' = $null
            'MaximumVariableCount' = $null
            'OFS' = $null
            'OutputEncoding' = $null
            'ProgressPreference' = $null
            'PSDefaultParameterValues' = $null
            'PSEmailServer' = $null
            'PSModuleAutoLoadingPreference' = $null
            'PSSessionApplicationName' = $null
            'PSSessionConfigurationName' = $null
            'PSSessionOption' = $null

            'ErrorActionPreference' = 'ErrorAction'
            'DebugPreference' = 'Debug'
            'ConfirmPreference' = 'Confirm'
            'WhatIfPreference' = 'WhatIf'
            'VerbosePreference' = 'Verbose'
            'WarningPreference' = 'WarningAction'
        }


        foreach ($entry in $vars.GetEnumerator())
        {
            if (([string]::IsNullOrEmpty($entry.Value) -or -not $Cmdlet.MyInvocation.BoundParameters.ContainsKey($entry.Value)) -and
                ($PSCmdlet.ParameterSetName -eq 'AllVariables' -or $filterHash.ContainsKey($entry.Name)))
            {
                $variable = $Cmdlet.SessionState.PSVariable.Get($entry.Key)
                
                if ($null -ne $variable)
                {
                    if ($SessionState -eq $ExecutionContext.SessionState)
                    {
                        Set-Variable -Scope 1 -Name $variable.Name -Value $variable.Value -Force
                    }
                    else
                    {
                        $SessionState.PSVariable.Set($variable.Name, $variable.Value)
                    }
                }
            }
        }

        if ($PSCmdlet.ParameterSetName -eq 'Filtered')
        {
            foreach ($varName in $filterHash.Keys)
            {
                if (-not $vars.ContainsKey($varName))
                {
                    $variable = $Cmdlet.SessionState.PSVariable.Get($varName)
                
                    if ($null -ne $variable)
                    {
                        if ($SessionState -eq $ExecutionContext.SessionState)
                        {
                            Set-Variable -Scope 1 -Name $variable.Name -Value $variable.Value -Force
                        }
                        else
                        {
                            $SessionState.PSVariable.Set($variable.Name, $variable.Value)
                        }
                    }
                }
            }
        }

    } # end

} # function Get-CallerPreference


Export-ModuleMember -Function 'ConvertTo-SecureString', 'ConvertFrom-SecureString', 'Get-CallerPreference'

ZIP:

ConvertTo-SecureFunctions