c-hive.psm1

function Connect-DataVerse{
    param(

        [string]$TenantID,
        [string]$ClientID,
        [string]$ClientSecret,
        [string]$DataVerseEnvironmentURL,
        [string]$CurrentApplication
    )

    $authBody = 
    @{
        client_id = $ClientID;
        client_secret = $ClientSecret;    
        scope = "$($DataVerseEnvironmentURL)/.default"    
        grant_type = 'client_credentials'
    }

    $oAuthTokenEndpoint = "https://login.microsoftonline.com/$TenantID/oauth2/v2.0/token"
    $authParams = 
    @{
        URI = $oAuthTokenEndpoint
        Method = 'POST'
        ContentType = 'application/x-www-form-urlencoded'
        Body = $authBody
    }

    $authRequest = Invoke-RestMethod @authParams -ErrorAction Stop
    $authRequest | Add-Member -MemberType NoteProperty -Name "DataVerseEnvironmentURL" -Value $DataVerseEnvironmentURL
    $authRequest | Add-Member -MemberType NoteProperty -Name "Application" -Value $CurrentApplication
    return $authRequest

}

function get-attachmentContent{
param($DVHeader, $tableName, $recordId,$attachmentColumn, $outputFilePath)

    $token = $DVHeader.access_token
    $DVURL = $DVHeader.DataVerseEnvironmentURL
    $queryUrl = "$DVURL/api/data/v9.1/$tableName($recordId)/$attachmentColumn"
    $attachmentInfo = Invoke-RestMethod -Uri $queryUrl -Method Get -Headers @{"Authorization" = "Bearer $token"} 
    $content = $attachmentInfo.value
    $fileBytes = [System.Convert]::FromBase64String($content)
    [System.IO.File]::WriteAllBytes($outputFilePath, $fileBytes)




}



function Get-DataVerseTableData{
    param(
        $AccessToken,
        $Table,
        $param = "NA"
    )
   
    #$param = "filter=emailaddress1 eq 'loop5@test.de'"


    if ($param -ne "NA")
    {
    
        $uri = $AccessToken.DataVerseEnvironmentURL + "/api/data/v9.2/$Table"  + '?$filter=' + "$param"
        
        $apiCallParams =
        @{
            URI = $uri
            Headers = @{
                "Authorization" = "$($AccessToken.token_type) $($AccessToken.access_token)" 
            }
            Method = 'GET'
        }
       $apiCallParams.URI.ToString()
    }
    else
    {
      
        $uri = $AccessToken.DataVerseEnvironmentURL + "/api/data/v9.2/$Table"

        $apiCallParams =
        @{
            URI =$uri
            Headers = @{
                "Authorization" = "$($AccessToken.token_type) $($AccessToken.access_token)" 
            }
            Method = 'GET'
        }
    }

    $result = Invoke-RestMethod @apiCallParams -ErrorAction Stop
    return $result
    
}

function New-DataVerseTableItem{
    param(
        $AccessToken,
        $Table,
        $Data
    )

    <#
    $data = @{
        "emailaddress1" = "value2@test.de";
        "nickname" = "value2";
        # Add more fields as needed
    }
    #>

    $uri = ($AccessToken.DataVerseEnvironmentURL + "/api/data/v9.2/$Table").ToString()
    $apiCallParams =
    @{
        
        Headers = @{
            "Authorization" = "$($AccessToken.token_type) $($AccessToken.access_token)" 
            "Content-Type" = "application/json"
        }
        Method = 'Post'
    }
  

    $TokenType = $AccessToken.token_type
    $TokenValue = $AccessToken.access_token
    
    $queryHeader = @{
        "Content-Type" = "application/json"
        "Authorization" = "$TokenType $TokenValue"
    }



    $jsonstring = ($data | ConvertTo-Json)
    $utf8JsonBytes = [System.Text.Encoding]::UTF8.GetBytes($jsonString)
    $result = Invoke-RestMethod -Method Post -Uri $uri  -Headers $queryHeader -Body $utf8JsonBytes
    return $result

}

function Update-DataVerseTableItem {
    param(
        [Parameter(Mandatory=$true)]
        [object]$AccessToken,
        
        [Parameter(Mandatory=$true)]
        [string]$Table,
        
        [Parameter(Mandatory=$true)]
        [string]$ItemId,
        
        [Parameter(Mandatory=$true)]
        [object]$Data
    )

    $uri = ($AccessToken.DataVerseEnvironmentURL + "/api/data/v9.2/$Table").ToString() + "(" + $ItemId + ")"
    $TokenType = $AccessToken.token_type
    $TokenValue = $AccessToken.access_token
    
    $queryHeader = @{
        "Content-Type" = "application/json"
        "Authorization" = "$TokenType $TokenValue"
    }

    try {
        $result = Invoke-RestMethod -Method Patch -Uri $uri -Headers $queryHeader -Body ($Data | ConvertTo-Json)
        return $result
    } catch {
        Write-Error "Failed to update item $ItemId in Dataverse table $Table. $_"
    }
}

function Upload-DataVerseTableFileToItem{
    param(
        [Parameter(Mandatory=$true)]
        [object]$AccessToken,

        [Parameter(Mandatory=$true)]
        $FullFilePath,
        
        [Parameter(Mandatory=$true)]
        [string]$Table,

        [Parameter(Mandatory=$true)]
        [string]$ItemId,

        [Parameter(Mandatory=$true)]
        [string]$FieldName,

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

    )

    write-host "xxxxx"    
    write-host "Uploading File"
    write-host $Table
    
    write-host $ItemId
    write-host $FieldName
    write-host $FileNameAtDataVerse
    write-host "xxxxxxx"


    $TokenType = $AccessToken.token_type
    $TokenValue = $AccessToken.access_token

    $queryHeader = @{
        "Authorization" = "$TokenType $TokenValue"
        "OData-MaxVersion" = "4.0"
        "OData-Version" = "4.0"
        "Accept" = "application/json"
        "Content-Type" = "application/octet-stream"
        "x-ms-file-name" = $FileNameAtDataVerse
    }
   
    
    $uri = ($AccessToken.DataVerseEnvironmentURL + "/api/data/v9.2/$Table").ToString() + "(" + $ItemId + ")/$FieldName"
    $FileContentInRAWBytes = ([System.IO.File]::ReadAllBytes($FullFilePath))

    $response = Invoke-RestMethod -Uri $uri -Method Put -Headers $queryHeader -Body $FileContentInRAWBytes

    write-host $response
    return $response
}
  

function get-IsTemplateExportAble{
    param ($msPKIPrivateKeyFlag)


[flags()]
enum custombitflags{
    CT_FLAG_ATTEST_NONE = 0
    CT_FLAG_REQUIRE_PRIVATE_KEY_ARCHIVAL = 1
    F2 = 2
    F4 = 4
    F8 = 8
    CT_FLAG_EXPORTABLE_KEY = 16
    CT_FLAG_STRONG_KEY_PROTECTION_REQUIRED = 32
    CT_FLAG_REQUIRE_ALTERNATE_SIGNATURE_ALGORITHM = 64
    CT_FLAG_REQUIRE_SAME_KEY_RENEWAL = 128
    CT_FLAG_USE_LEGACY_PROVIDER = 256
    CT_FLAG_EK_TRUST_ON_USE = 512
    CT_FLAG_EK_VALIDATE_CERT = 1024
    CT_FLAG_EK_VALIDATE_KEY = 2048
    CT_FLAG_ATTEST_PREFERRED = 4096
    CT_FLAG_ATTEST_REQUIRED = 8192
    CT_FLAG_ATTESTATION_WITHOUT_POLICY = 16384
    F32768  = 32768
    F65536 = 65536
    F131072 = 131072
    F262144 = 262144
    F524288 = 524288
    F983040 = 983040 
    F1048576 = 1048576
    F2097152 = 2097152
    F4194304 = 4194304
    F8388608 = 8388608
    F16777216 = 16777216
    F33554432 = 33554432
    F67108864 = 67108864
    F134217728 = 134217728
    F268435456 = 268435456
}

[custombitflags]$f = $msPKIPrivateKeyFlag
if($f.HasFlag([custombitflags]::CT_FLAG_EXPORTABLE_KEY)){$exp = "1"}else{$exp = "0"}
return $exp
}
function Convert-ByteArrayToPeriodOfDays ([Byte[]]$ByteArray) {
    <#
    .SYNOPSIS
    Converts a ByteArray to a period of days (certificate specific)
    .EXAMPLE
    Convert-ByteArrayToPeriodOfDays $byteArray
    #>

    write-verbose "--Executing: Convert-ByteArrayToPeriodOfDays"
    [array]::Reverse($ByteArray)
    $LittleEndianByte = -join ($ByteArray | %{"{0:x2}" -f $_})
    $Value = [Convert]::ToInt64($LittleEndianByte,16) * -.0000001
    return [string]($Value/3600/24) # result = days
}
function start-CertReqFSubmitAttrib() {
  <#
    .SYNOPSIS
    Runs certreq -f -submit -attrib ...
  #>


        param(
        [Parameter(mandatory=$true)]$full_ca_name,
        [Parameter(mandatory=$true)]$CertReqName,
        [Parameter(mandatory=$true)]$CertName,
        [Parameter(mandatory=$true)]$template_name,
        [Parameter(mandatory=$true)]$CertNameP7B,
        [Parameter(mandatory=$true)]$resultpath
        


        )
        $template =  "CertificateTemplate:" + $template_name
        #$command = ("-f -submit -attrib "+[char]34+$template+[char]34+" -config "+[char]34+$full_ca_name+[char]34+" "+[char]34+$CertReqName+[char]34+" "+[char]34+$CertName+[char]34 + " " +[char]34+$CertNameP7B+[char]34 )
        $command =  ('-f -submit -attrib "' + $template + '" -config "' + $full_ca_name+ '" "' + $CertReqName + '" "'+ $CertName + '" "' + $CertNameP7B + '"' )


            Remove-Item $resultpath -Confirm:$false -Force -ErrorAction SilentlyContinue
            $process = start-process -PassThru  certreq $command -RedirectStandardOutput $resultpath
            try {
                Wait-Process -id $process.ID -timeout 30 -ErrorAction stop; 
                $message = Get-Content $resultpath
            }
            catch {
                $message = "Error executing: certreq" + $command
            }
            return $message

        return $result

}
function start-CertreqAccept(){
  <#
    .SYNOPSIS
    Runs certreq -accept on a remote server with given parameters
  #>

        param(
        [Parameter(mandatory=$true)]$CertName
        )
        
        $command =  (" -accept "+ $CertName )
        write-host $command
        $process = start-process  -PassThru  certreq $command  -Verb runas

        try {
            Wait-Process -id $process.ID -timeout 10 -ErrorAction stop; $message = ""
            }
        catch {
            $message = "Error executing: certreq "+ $command 
        }

        return $message
}








# ----------------OLD STUFF BELOW -----------------
function Issue-PendingRequest {
[CmdletBinding()]
  param(
    [Parameter(mandatory=$true)]$ps_session,
    [Parameter(mandatory=$true)][string]$CAConfig,
    [Parameter(mandatory=$true)][int]$RequestID
  )


    $status = Invoke-Command -Session $ps_session -ArgumentList $CAConfig,$RequestID -ScriptBlock {
        $CAConfig = $args[0]
        $RequestID = $args[1]
        try {$CertAdmin = New-Object -ComObject CertificateAuthority.Admin}
        catch {Write-Warning "Unable to instantiate ICertAdmin2 object!"; return}
        try {
            $status = switch ($CertAdmin.ResubmitRequest($CAConfig,$RequestID)) {
                0 {"The request was not completed."}
                1 {"The request failed."}
                2 {"The request was denied."}
                3 {"The certificate was issued."}
                4 {"The certificate was issued separately"}
                5 {"The request was taken under submission."}
                6 {"The certificate is revoked."}
            }
   
          }
        catch {$_; return}
        return $status
    }
    return $status
  #Issue-PendingRequest -CAConfig "wbg-pki.tavv.at\WBC-CA" -RequestID 12

}

function Deny-PendingRequest {
[CmdletBinding()]
  param(
    [Parameter(mandatory=$true)]$ps_session,
    [Parameter(mandatory=$true)][string]$CAConfig,
    [Parameter(mandatory=$true)][int]$RequestID
  )


    $status = Invoke-Command -Session $ps_session -ArgumentList $CAConfig,$RequestID -ScriptBlock {
        $CAConfig = $args[0]
        $RequestID = $args[1]
        try {$CertAdmin = New-Object -ComObject CertificateAuthority.Admin}
        catch {Write-Warning "Unable to instantiate ICertAdmin2 object!"; return}
        try {
            $status = $CertAdmin.DenyRequest($CAConfig,$RequestID)
          }
        catch {$_; return}
        return $status
    }
    return $status
  #Deny-PendingRequest -CAConfig "wbg-pki.tavv.at\WBC-CA" -RequestID 12

}

function start-CertReqNew() {
  <#
    .SYNOPSIS
    Runs certreq -new on a remote server with given parameters
    .EXAMPLE
    start-CertReqNew -ps_session $remote_ps_session -inf_path $filepath_to_inf_file -CertReqName $filepath_to_req_file
  #>


        param(
        [Parameter(mandatory=$true)]$ps_session,
        [Parameter(mandatory=$true)]$inf_path,
        [Parameter(mandatory=$true)]$CertReqName,
        [Parameter(Mandatory=$false)][System.Boolean]$noverbose

        )

        $command = " -f -new "+$inf_path + " " + $CertReqName
        out-logOK -noevent $noverbose -eventsource "SPCertMgmt_Enrollment.psm1"  -message ("Executing certreq " + $command) -id 480
        $result = Invoke-Command -Session $ps_session  -ArgumentList $command -ScriptBlock  {
          $process = start-process -PassThru certreq ($args[0]) -Verb runas
            try {Wait-Process -id $process.ID -timeout 30 -ErrorAction stop; $message =""}
            catch {
                $message = "Error executing: certreq " + $args[0]
            }
        return $message
        }
        return $result
        out-logError -eventsource "SPCertMgmt_Enrollment.psm1" -message $result -id 490
}

function start-CertReqRetrieveConfig (){
        param(
        [Parameter(mandatory=$true)]$ps_session,
        [Parameter(mandatory=$true)]$full_ca_name,
        [Parameter(mandatory=$true)]$cert_req_id,
        [Parameter(mandatory=$true)]$CertName,
        [Parameter(mandatory=$true)]$CertNameP7B,
        [Parameter(Mandatory=$false)][System.Boolean]$noverbose
        )

    $command = ("-retrieve -config "+ [char]34+ $full_ca_name +[char]34 +" "+ $cert_req_id +" "+ [char]34 +$CertName +[char]34  +" " +[char]34 + $CertNameP7B+[char]34  )
    out-logOK -noevent $noverbose -eventsource "SPCertMgmt_Enrollment.psm1" -message ("Executing: certreq $command") -id 606

    $result = Invoke-Command -Session $ps_session  -ArgumentList $command -ScriptBlock  { 
        $process = start-process -PassThru certreq $args[0]
     
        try {Wait-Process -id $process.ID -timeout 30 -ErrorAction stop; $message = ""}
        catch {$message = "Error executing: certreq "+ $args[0]}
        return $message
    }
    return $result
    out-logError -eventsource "SPCertMgmt_Enrollment.psm1" -message $result -id 576

}







function start-CertReqFSubmitConfig() {
  <#
    .SYNOPSIS
    Runs certreq -f -submit -config on a remote server with given parameters
  #>


        param(
        [Parameter(mandatory=$true)]$ps_session,
        [Parameter(mandatory=$true)]$full_ca_name,
        [Parameter(mandatory=$true)]$CertReqName,
        [Parameter(mandatory=$true)]$CertName,
        [Parameter(mandatory=$true)]$output_to,
        [Parameter(mandatory=$true)]$CertNameP7B
        
        )

        $command = ("-f -submit -config "+[char]34+$full_ca_name[0]+[char]34+ " "+[char]34+$CertReqName[1]+[char]34+" "+[char]34+$CertName[2]+[char]34+ " " +[char]34+$CertNameP7B[4]+[char]34)
        $result = Invoke-Command -Session $ps_session -ArgumentList $command, $output_to  -ScriptBlock  {
            Remove-Item "result.txt" -Confirm:$false -Force -ErrorAction SilentlyContinue
            $process = start-process -verb runas -PassThru  certreq $command -RedirectStandardOutput ("result.txt")
            try {Wait-Process -id $process.ID -timeout 30 -ErrorAction stop; $message = Get-Content "result.txt"}
            catch {$message = "Error executing: certreq " + $command }

            return $message
        }
        return $result
}

function start-CertUtilP() {
  <#
    .SYNOPSIS
    Runs certutil -p on a remote server with given parameters
  #>

        param(
        [Parameter(mandatory=$true)]$ps_session,
        [Parameter(mandatory=$true)]$CertName,
        [Parameter(mandatory=$true)]$PFXName,
        [Parameter(mandatory=$true)]$password,
        [Parameter(Mandatory=$false)][System.Boolean]$noverbose


        )
        $cert_data = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($CertName)
        $command = (" -p "+ $password+" -exportpfx My "+ $cert_data.Thumbprint +" "+$PFXName)
        out-logOK -noevent $noverbose -eventsource "SPCertMgmt_Enrollment.psm1" -message ("Executing: certutil " + $command) -id 662

        $result = Invoke-Command -Session $ps_session  -ArgumentList $command  -ScriptBlock  {
            $process = start-process -PassThru certutil ($args[0]) -Verb runas  #export pfx
            try {Wait-Process -id $process.ID -timeout 30 -ErrorAction stop; $message = ""}
            catch {$message = "Error executing: certutil "+$args[0]}
            return $message
        }
        return $result
        out-logError -eventsource "SPCertMgmt_Enrollment.psm1" -message $result -id 671
}


function start-RevokeCertificate() {
  <#
    .SYNOPSIS
     
    Runs certutil -config CANAME -revoke CERTSERIAL REASONNUMBER on a remote server with given parameters
  #>

     param(
        [Parameter(mandatory=$true)]$ps_session,
        [Parameter(mandatory=$true)]$full_ca_name,
        [Parameter(mandatory=$true)]$CertificateSerialNumber,
        [Parameter(mandatory=$true)]$ReasonNumber,
        [Parameter(Mandatory=$false)][System.Boolean]$noverbose

        )


        $command = ("-config "+[char]34+$full_ca_name+[char]34+" -revoke "+[char]34+$CertificateSerialNumber+[char]34+ " " + $ReasonNumber )
        out-logOK -noevent $noverbose -eventsource "SPCertMgmt_Enrollment.psm1"  -message ("Executing CertUtil "+ $command) -id 543
        $result = Invoke-Command -Session $ps_session  -ArgumentList $command -ScriptBlock `
        {
            $process = start-process -PassThru  certutil ($args[0]) -Verb runas
            try{Wait-Process -id $process.ID -timeout 30 -ErrorAction stop; $message = ""}
            catch {$message = "Error executing: certutil "+$args[0]}
            return $message
        }

    return $result         
    out-logError -eventsource "SPCertMgmt_Enrollment.psm1" -message $result -id 553

}



function get-CertificateApprovalStatus() {

     param(
        [Parameter(mandatory=$true)]$ps_session,
        [Parameter(mandatory=$true)]$full_ca_name,
        [Parameter(mandatory=$true)]$cert_req_id,
        [Parameter(Mandatory=$false)][System.Boolean]$noverbose


        )
    
    out-logOK -noevent $noverbose -eventsource "SPCertMgmt_Enrollment.psm1"  -message ("Get Certificate Approval Status from CA " + $full_ca_name +" for Request: "+$cert_req_id +" on CA " +$full_ca_name) -id 503
    $approval_status = Invoke-Command -Session $ps_session  -ArgumentList $full_ca_name,$cert_req_id -ScriptBlock `
    {
        $CV_OUT_BASE64HEADER = 0
        $CV_OUT_BINARY = 2
    
        # Connecting to the Certificate Authority
        $objCertView = New-Object -ComObject CertificateAuthority.View
        $objCertView.OpenConnection($args[0])
 
        # Place necessary columns in the view and set filter
        $objCertView.SetResultColumnCount(1)
        $Column = $objCertView.GetColumnIndex($false,"RequestID")
        $objCertView.SetResultColumn($Column)
        $objCertView.SetRestriction($Column,1,0,([int]$args[1]))
        $Column = $objCertView.GetColumnIndex($False,"Disposition")
        #$objCertView.SetResultColumn($Column)
        $objCertView.SetRestriction($Column,1,0,20)
        $objCertViewRow = $objCertView.OpenView()
        $objCertViewRow.Reset()
        $objCertViewRow.Next()
    }
    return $approval_status
}
function get-CertificateDenyStatus() {

     param(
        [Parameter(mandatory=$true)]$ps_session,
        [Parameter(mandatory=$true)]$full_ca_name,
        [Parameter(mandatory=$true)]$cert_req_id,
        [Parameter(Mandatory=$false)][System.Boolean]$noverbose


        )
    
    out-logOK -noevent $noverbose -eventsource "SPCertMgmt_Enrollment.psm1"  -message ("Get Certificate Deny Status from CA " + $full_ca_name +" for Request: "+$cert_req_id +" on CA " +$full_ca_name) -id 503
    $approval_status = Invoke-Command -Session $ps_session  -ArgumentList $full_ca_name,$cert_req_id -ScriptBlock `
    {
        $CV_OUT_BASE64HEADER = 0
        $CV_OUT_BINARY = 2
    
        # Connecting to the Certificate Authority
        $objCertView = New-Object -ComObject CertificateAuthority.View
        $objCertView.OpenConnection($args[0])
 
        # Place necessary columns in the view and set filter
        $objCertView.SetResultColumnCount(1)
        $Column = $objCertView.GetColumnIndex($false,"RequestID")
        $objCertView.SetResultColumn($Column)
        $objCertView.SetRestriction($Column,1,0,([int]$args[1]))
        $Column = $objCertView.GetColumnIndex($False,"Disposition")
        #$objCertView.SetResultColumn($Column)
        $objCertView.SetRestriction($Column,1,0,31)
        $objCertViewRow = $objCertView.OpenView()
        $objCertViewRow.Reset()
        $objCertViewRow.Next()
    }
    return $approval_status
}
function get-CertificatePendingApprovals() {

    param(
        [Parameter(mandatory=$true)]$ps_session,
        [Parameter(mandatory=$true)]$full_ca_name,
        [Parameter(Mandatory=$false)][System.Boolean]$noverbose
    )
  
    $pending_requests = Invoke-Command -Session $ps_session -ArgumentList $full_ca_name -ScriptBlock {
        $full_ca_name = $args[0]
        # Establish connection to Certificate server
        $objCertView = New-Object -Com CertificateAuthority.View
        $objCertView.OpenConnection($full_ca_name)

        # Define the numbers of columns
        $NumberOfColumns=6
        $objCertView.SetResultColumnCount($NumberOfColumns)

    

       
        $Index01 = $objCertView.GetColumnIndex($False, "RequestID")
        $Index02 = $objCertView.GetColumnIndex($False, "CommonName")
        $Index03 = $objCertView.GetColumnIndex($False, "RequesterName")
        $Index04 = $objCertView.GetColumnIndex($False, "SubmittedWhen")
        $Index05 = $objCertView.GetColumnIndex($False, "CertificateTemplate")
        $Index06 = $objCertView.GetColumnIndex($False, "RawPublicKey")
        $objCertView.SetResultColumn($Index01)
        $objCertView.SetResultColumn($Index02)
        $objCertView.SetResultColumn($Index03)
        $objCertView.SetResultColumn($Index04)
        $objCertView.SetResultColumn($Index05)
        $objCertView.SetResultColumn($Index06)
        $objCertView.SetRestriction($objCertView.GetColumnIndex($false,"Request Disposition"),1,0,9)

 

        $RowObj= $objCertView.OpenView()
     
        [void]$RowObj.Next()
        

        #region define data table
        $pending_request_table = New-Object system.Data.DataTable
        $col1 = New-Object system.Data.DataColumn RequestID
        $col2 = New-Object system.Data.DataColumn CommonName
        $col3 = New-Object system.Data.DataColumn RequesterName
        $col4 = New-Object system.Data.DataColumn SubmittedWhen
        $col5 = New-Object system.Data.DataColumn CertificateTemplate
        $col6 = New-Object system.Data.DataColumn RawPublicKey   
        $pending_request_table.columns.add($col1)
        $pending_request_table.columns.add($col2)
        $pending_request_table.columns.add($col3)
        $pending_request_table.columns.add($col4)
        $pending_request_table.columns.add($col5)
        $pending_request_table.columns.add($col6)    
        function Add-PendingCertInfo
        {param ( $RequestID,$CommonName,$RequesterName,$SubmittedWhen,$CertificateTemplate,$RawPublicKey) 
            $newRow = $pending_request_table.NewRow()
                $newRow.RequestID = $RequestID
                $newRow.CommonName = $CommonName
                $newRow.RequesterName=$RequesterName
                $newRow.SubmittedWhen= $SubmittedWhen
                $newrow.CertificateTemplate = $CertificateTemplate
                $newrow.RawPublicKey = $RawPublicKey   
                $pending_request_table.rows.add($newRow)
            }
        #endregion



        Do
        {
            $cert = $null
            $cert_data = $null
            try{
                $ColObj = $RowObj.EnumCertViewColumn()
                [void]$ColObj.Next()
    
                Do {
                    $Cert+=$ColObj.GetValue(1).tostring() + ";"
                } Until ($ColObj.Next() -eq -1)
        
                Clear-Variable ColObj
               # write-host $cert -fore Cyan
           
                $cert_data = $cert.Split(";")
                Add-PendingCertInfo -RequestID $cert_data[0] -CommonName $cert_data[1] -RequesterName $cert_data[2] -SubmittedWhen $cert_data[3] -CertificateTemplate $cert_data[4] -RawPublicKey $cert_data[5]
            }
            catch{}
        } Until ($Rowobj.Next() -eq -1 )
        Return $pending_request_table
    }
    return $pending_requests
 }  


function remove-Privatekey() {
  <#
    .SYNOPSIS
    Runs remove-privatekey -ps_session $pssession -thumbpring $certificate_thumbprint
  #>

        param(
        [Parameter(mandatory=$true)]$ps_session,
        [Parameter(mandatory=$true)]$ThumbPrint,
        [Parameter(Mandatory=$false)][System.Boolean]$noverbose

        )
        out-logOK -noevent $noverbose -eventsource "SPCertMgmt_Enrollment.psm1" -message ("Removing Private Key for Certificate Thumbprint " + $ThumbPrint) -id 836
        Invoke-Command -Session $ps_session  -ArgumentList $ThumbPrint  -ScriptBlock  {  
            $ThumbPrint = $Args[0]                  
            cd Cert:\LocalMachine\my\
            $old_eap = $ErrorActionPreference 
            $ErrorActionPreference = "SilentlyContinue"
            try{dir $ThumbPrint | Remove-Item -deletekey}catch{}
            $ErrorActionPreference = $old_eap 
        }
}


function New-CHiveEventLog {
  <#
    .SYNOPSIS
    Creates new EventLog Entries
    .EXAMPLE
    New-CHiveEventLog -eventsource "my Custom EventSource" -severity "Error" -id 4711 -message "This is just a custom string which appears in the eventlog"
  #>


    Param ($eventsource,$severity, $id, $message)
    $SOURCE="C-Hive by vivaXite"
    if ([system.diagnostics.eventlog]::SourceExists($eventsource) -eq $false){
        [system.diagnostics.EventLog]::CreateEventSource($eventsource, $SOURCE)
    }
    Write-EventLog -LogName $SOURCE -Source $eventsource.tolower() -EventId $id -EntryType $severity -Message ($message) -ComputerName ([System.Net.Dns]::GetHostName()) -Category 0
}
function out-logheader(){
    Param ($eventsource, $id, $message)

    if ($message -ne "")
    {
        $len = 80
        $heading_start = ([char]9474).tostring() + ([char]32).ToString() + $(([char]32).ToString() * (($len/2)-($message.Length/2)-1))
        $heading_mid = $message
        $cur_len = $heading_start.Length+$heading_mid.Length
        $heading_end = $(([char]32).ToString() * ($len-$cur_len)) + ([char]32).ToString() + ([char]9474).tostring() 

        $heading = $heading_start+$heading_mid+$heading_end
        $topline = ([char]9484).ToString() + $(([char]9472).ToString() * ($len)) + ([char]9488).ToString()
        $botline = ([char]9492).ToString() + $(([char]9472).ToString() * ($len)) + ([char]9496).ToString()
        $boxtitle = $topline + "`n" + $heading + "`n" + $botline
        write-host $boxtitle -fore Green
        New-CHiveEventLog -eventsource $eventsource -severity "Information" -id $id -message $message
    }
}
function out-logOK(){
    Param ($eventsource, $id, $message)
    if ($message -ne "")
    {

        write-host ($eventsource + " > ") -fore red -BackgroundColor Black -NoNewline
        write-host $message -fore Green -BackgroundColor Black

        New-CHiveEventLog -eventsource $eventsource -severity "Information" -id $id -message $message
    }
}
function out-logWarn(){
    Param ($eventsource, $id, $message) 
    if ($message -ne "")
    {

            write-host ($eventsource + " > ") -fore red -BackgroundColor Black -NoNewline 
            write-host $message -fore Yellow -BackgroundColor Black
            New-CHiveEventLog -eventsource $eventsource -severity "Warning" -id $id -message $message
    }
}
function out-logError(){
    Param ($eventsource, $id, $message) 
    if ($message -ne "")
    {

            write-host $eventsource -fore red -BackgroundColor Black
            write-host "ERROR MESSAGE BEGIN:"  $("*" * 120) -fore red -BackgroundColor Black
            write-host $message -fore Red -BackgroundColor Black
            write-host "ERROR MESSAGE END: "  $("*" * 120) -fore red -BackgroundColor Black
            New-CHiveEventLog -eventsource $eventsource -severity "Error" -id $id -message $message
    }
}

export-modulemember -function *