WitSie.Package.ps1

#------------------------------------------------------------------------
# Source File Information (DO NOT MODIFY)
# Source ID: 19576761-c8c8-4de7-b7f3-bee7a76c94b9
# Source File: C:\Data\onedrive\OneDrive - Witcon AB\Witcon\Witcon\Dokuments\SAPIEN\PowerShell Studio\Projects\WitSie\WitSie.psproj
#------------------------------------------------------------------------
#region Project Recovery Data (DO NOT MODIFY)
<#RecoveryData:
lwMAAB+LCAAAAAAABACtk0FPwjAUx+8kfIdlR5MxpshYLDsYQsJFDSN6NKV7k0rXLm2H4Ke3WwvO
EG+7vPb/7+v77b10aA1EHECeFljjdDjwPPQixScQ7WUnTnZScPoN+dxfYqbAb80lZRrk3L8ZVSp6
aGJpl9wu0bFk7aZoozLROjtg1Ugftd+CDOoVpKKCp7ejCIVn4c4MBVaLNEru42k8jQIyI7NgkkMc
bOPiLtgCxDiekmSyTVDokt1V18HmVEE6RmFXnosLlhucF3ZpygknvceaMtP52E8zjaWuq6YZy/ov
08t2WHbGtYYCJHACy5oTbbqb+yt+EHsINqD0u5mVnza7Zmp9VebwRWqlRQnSAjpGnxxFoXCesqCu
0ycpo0DLSkg3sIvsuRsmyL4CSUV+aefXumJZYd/M5Y1Z9SzpB+WYNQlPuIT0jWrz0aZEZdJQeHU+
HKDwz4/4A9lZmk2XAwAA#>

#endregion
<#
    .NOTES
    --------------------------------------------------------------------------------
     Code generated by: SAPIEN Technologies, Inc., PowerShell Studio 2021 v5.8.191
     Generated on: 2021-09-29 16:37
     Generated by: Björn Willim
     Organization: Witcon AB
    --------------------------------------------------------------------------------
    .DESCRIPTION
        Script generated by PowerShell Studio 2021
#>




#region Source: Startup.pss
#region File Recovery Data (DO NOT MODIFY)
<#RecoveryData:
YQAAAB+LCAAAAAAABACzCUpNzi9LLap0SSxJVAAyijPz82yVjPWMlOx4uRQUbPyLMtMz8xJz3DJz
Uv0Sc1PtgksSi0pKC/QKiott9DFkebls9JGNtAMAXtMIOWEAAAA=#>

#endregion
#----------------------------------------------
#region Import Assemblies
#----------------------------------------------
#endregion Import Assemblies

# Warning: Do not rename Start-MyService, Invoke-MyService and Stop-MyService functions


function Start-MyService
{
    # Place one time startup code here.
    # Initialize global variables and open connections if needed
    $global:bRunService = $true
    $global:bServiceRunning = $false
    $global:bServicePaused = $false
}

function Invoke-MyService
{
    $global:bServiceRunning = $true
    while($global:bRunService) {
        try 
        {
            if($global:bServicePaused -eq $false) #Only act if service is not paused
            {
                #Place code for your service here
                #e.g. $ProcessList = Get-Process solitaire -ErrorAction SilentlyContinue
                $Exp= get-WITsie -Token 'e038e337-0fe5-4a16-bb03-17da2c0c8289'
                # Use Write-Host or any other PowerShell output function to write to the System's application log
                $Exp|Export-Csv -Path c:\Data\sietest.csv -Encoding Default -NoTypeInformation
            }
        }
        catch
        {
            # Log exception in application log
            Write-Host $_.Exception.Message 
        }
        # Adjust sleep timing to determine how often your service becomes active.
        if($global:bServicePaused -eq $true) 
        {
            Start-Sleep -Seconds 3600 # if the service is paused we sleep longer between checks.
        }
        else 
        {
            Start-Sleep â€“Seconds 360 # a lower number will make your service active more often and use more CPU cycles
        }
    }
    $global:bServiceRunning    = $false
}

function Stop-MyService
{
    $global:bRunService = $false # Signal main loop to exit
    $CountDown = 30 # Maximum wait for loop to exit
    while($global:bServiceRunning -and $Countdown -gt 0)
    {
        Start-Sleep -Seconds 1 # wait for your main loop to exit
        $Countdown = $Countdown - 1
    }
    # Place code to be executed on service stop here
    # Close files and connections, terminate jobs and
    # use remove-module to unload blocking modules
}

function Pause-MyService
{
    # Service is being paused
    # Save state
    $global:bServicePaused = $true
    # Note that the thread your PowerShell script is running on is not suspended on 'pause'.
    # It is your responsibility in the service loop to pause processing until a 'continue' command is issued.
    # It is recommended to sleep for longer periods between loop iterations when the service is paused.
    # in order to prevent excessive CPU usage by simply waiting and looping.
}

function Continue-MyService
{
    # Service is being continued from a paused state
    # Restore any saved states if needed
    $global:bServicePaused = $false
}
<#
    .NOTES
    ===========================================================================
     Created with: SAPIEN Technologies, Inc., PowerShell Studio 2021 v5.8.191
     Created on: 2021-09-06 11:01
     Created by: Björn Willim
     Organization: Witcon AB
     Filename: Test.ps1
    ===========================================================================
    .DESCRIPTION
        A description of the file.
#>

function get-WITsieToken
{
    [CmdletBinding()]
    param (
        [Parameter(Position = 0, Mandatory = $true)]
        $Integration_user_API_code
    )
    begin
    {
        try
        {
        }
        catch
        {
        }
    }
    process
    {
        try
        {
            $ClientSecret = 'wa5zIksMZ6'
            $Params = @{
                "Uri"    = 'https://api.fortnox.se/3/sie/4?financialyear=1'
                #"Uri" ="https://apps.fortnox.se/oauth-v1/token"
                "Method" = 'GET'
                "Header" = @{
                    "Authorization-Code" = $Integration_user_API_code
                    "Client-Secret"         = $ClientSecret
                    "Content-Type"         = "application/json"
                    "Accept"             = "application/json"
                }
                "Body"   = @{ }
            }
            
            $token = Invoke-RestMethod @Params
            $token.Authorization.AccessToken
            Write-Host "Token fetched "
        }
        catch
        {
            Write-Error "Could not fetch Token"
        }
    }
    end
    {
        try
        {
        }
        catch
        {
        }
    }
}

<#
    .SYNOPSIS
        A brief description of the get-WITsie function.
 
    .DESCRIPTION
        A detailed description of the get-WITsie function.
 
    .PARAMETER Token
        The description of a the ParameterA parameter.
 
    .PARAMETER ParameterB
        The description of a the ParameterB parameter.
 
    .EXAMPLE
        PS C:\> get-WITsie -ParameterA 'One value' -ParameterB 32
        'This is the output'
        This example shows how to call the get-WITsie function with named parameters.
 
    .EXAMPLE
        PS C:\> get-WITsie 'One value' 32
        'This is the output'
        This example shows how to call the get-WITsie function with positional parameters.
 
    .INPUTS
        System.String,System.Int32
 
    .OUTPUTS
        System.String
 
    .NOTES
        For more information about advanced functions, call Get-Help with any
        of the topics in the links listed below.
 
    .LINK
        about_functions_advanced
 
    .LINK
        about_comment_based_help
 
    .LINK
        about_functions_advanced_parameters
 
    .LINK
        about_functions_advanced_methods
#>

function get-WITsie
{
    [CmdletBinding()]
    param (
        [Parameter(Position = 0, Mandatory = $true)]
        $Token
    )
    begin
    {
        try
        {
        }
        catch
        {
        }
    }
    process
    {
        try
        {
            $ClientSecret = 'wa5zIksMZ6'
            $Params = @{
                "Uri"    = 'https://api.fortnox.se/3/sie/4?financialyear=1'
                "Method" = 'GET'
                "Header" = @{
                    "Access-Token"  = $token
                    "Client-Secret" = $ClientSecret
                    "Content-Type"  = "application/json"
                    "Accept"        = "application/json"
                }
                "Body"   = @{ }
            }
            
            $b = Invoke-RestMethod @Params
            $b
            Write-Host
        }
        catch
        {
        }
    }
    end
    {
        try
        {
        }
        catch
        {
        }
    }
}

<#
    .SYNOPSIS
        A brief description of the set-WITsieTokenstore function.
 
    .DESCRIPTION
        A detailed description of the set-WITsieTokenstore function.
 
    .PARAMETER Token
        The description of a the Token parameter.
 
    .PARAMETER Company
        The description of a the Company parameter.
 
    .EXAMPLE
        PS C:\> set-WITsieTokenstore -Token 'One value' -Company 32
        'This is the output'
        This example shows how to call the set-WITsieTokenstore function with named parameters.
 
    .EXAMPLE
        PS C:\> set-WITsieTokenstore 'One value' 32
        'This is the output'
        This example shows how to call the set-WITsieTokenstore function with positional parameters.
 
    .INPUTS
        System.String,System.Int32
 
    .OUTPUTS
        System.String
 
    .NOTES
        For more information about advanced functions, call Get-Help with any
        of the topics in the links listed below.
 
    .LINK
        about_functions_advanced
 
    .LINK
        about_comment_based_help
 
    .LINK
        about_functions_advanced_parameters
 
    .LINK
        about_functions_advanced_methods
#>

function set-WITsieTokenstore
{
    [CmdletBinding()]
    param (
        [Parameter(Position = 0, Mandatory = $true)]
        $Token,
        [Parameter(Position = 1)]
        $Company
    )
    begin
    {
        try
        {
        }
        catch
        {
        }
    }
    process
    {
        try
        {
            $Work = $Token.split('-')
            $enc = $work[2]
            $E_2 = [convert]::toint64($enc, 16)
            
            
        }
        catch
        {
        }
    }
    end
    {
        try
        {
        }
        catch
        {
        }
    }
}
#endregion Source: Startup.pss

#region Source: Test.ps1
function Invoke-Test_ps1
{
    <#
        .NOTES
        ===========================================================================
         Created with: SAPIEN Technologies, Inc., PowerShell Studio 2021 v5.8.191
         Created on: 2021-09-06 11:01
         Created by: Björn Willim
         Organization: Witcon AB
         Filename: Test.ps1
        ===========================================================================
        .DESCRIPTION
            A description of the file.
    #>

    function get-WITsieToken
    {
        [CmdletBinding()]
        param (
            [Parameter(Position = 0, Mandatory = $true)]
            $Integration_user_API_code
        )
        begin
        {
            try
            {
            }
            catch
            {
            }
        }
        process
        {
            try
            {
                $ClientSecret = 'wa5zIksMZ6'
                $Params = @{
                    "Uri"    = 'https://api.fortnox.se/3/sie/4?financialyear=1'
                    #"Uri" ="https://apps.fortnox.se/oauth-v1/token"
                    "Method" = 'GET'
                    "Header" = @{
                        "Authorization-Code" = $Integration_user_API_code
                        "Client-Secret"         = $ClientSecret
                        "Content-Type"         = "application/json"
                        "Accept"             = "application/json"
                    }
                    "Body"   = @{ }
                }
                
                $token = Invoke-RestMethod @Params
                $token.Authorization.AccessToken
                Write-Host "Token fetched "
            }
            catch
            {
                Write-Error "Could not fetch Token"
            }
        }
        end
        {
            try
            {
            }
            catch
            {
            }
        }
    }
    #
    <#
        .SYNOPSIS
            A brief description of the get-WITsie function.
     
        .DESCRIPTION
            A detailed description of the get-WITsie function.
     
        .PARAMETER Token
            The description of a the ParameterA parameter.
     
        .PARAMETER ParameterB
            The description of a the ParameterB parameter.
     
        .EXAMPLE
            PS C:\> get-WITsie -ParameterA 'One value' -ParameterB 32
            'This is the output'
            This example shows how to call the get-WITsie function with named parameters.
     
        .EXAMPLE
            PS C:\> get-WITsie 'One value' 32
            'This is the output'
            This example shows how to call the get-WITsie function with positional parameters.
     
        .INPUTS
            System.String,System.Int32
     
        .OUTPUTS
            System.String
     
        .NOTES
            For more information about advanced functions, call Get-Help with any
            of the topics in the links listed below.
     
        .LINK
            about_functions_advanced
     
        .LINK
            about_comment_based_help
     
        .LINK
            about_functions_advanced_parameters
     
        .LINK
            about_functions_advanced_methods
    #>

    function get-WITsie {
        [CmdletBinding()]
        param(
            [Parameter(Position=0, Mandatory=$true)]
            $Token,
            [Parameter(Position = 1, Mandatory = $true)]
            $Fiscalyear    )
        begin {
            try {
            }
            catch {
            }
        }
        process {
            try {
                $ClientSecret = 'wa5zIksMZ6'
                $Params = @{
                    "Uri"    = "https://api.fortnox.se/3/sie/4?financialyear=$fiscalyear "
                    "Method" = 'GET'
                    "Header" = @{
                        "Access-Token"  = $token
                        "Client-Secret" = $ClientSecret
                        "Content-Type"  = "application/json"
                        "Accept"        = "application/json"
                    }
                    "Body"     = @{ }
                    
                }
                
                
                $b = Invoke-WebRequest @Params
                $enc = [System.Text.Encoding]::GetEncoding(850)
                $text = $enc.GetString($b.Content)
                $text.Split([Environment]::NewLine)
            }
            catch {
            }
        }
        end {
            try {
            }
            catch {
            }
        }
    }
    
    function get-WITsieFiscalyears
    {
        [CmdletBinding()]
        param (
            [Parameter(Position = 0, Mandatory = $true)]
            $Token
        )
        begin
        {
            try
            {
            }
            catch
            {
            }
        }
        process
        {
            try
            {
                $ClientSecret = 'wa5zIksMZ6'
                $Params = @{
                    "Uri"    = 'https://api.fortnox.se/3/financialyears'
                    "Method" = 'GET'
                    "Header" = @{
                        "Access-Token"  = $token
                        "Client-Secret" = $ClientSecret
                        "Content-Type"  = "application/json"
                        "Accept"        = "application/json"
                    }
                    "Body"   = @{ }
                    
                }
                
                
                $b = Invoke-WebRequest @Params
                $text= convertfrom-json ($b.Content)
                $text.FinancialYears
                
            }
            catch
            {
            }
        }
        end
        {
            try
            {
            }
            catch
            {
            }
        }
    }
    
    <#
        .SYNOPSIS
            A brief description of the set-WITsieTokenstore function.
     
        .DESCRIPTION
            A detailed description of the set-WITsieTokenstore function.
     
        .PARAMETER Token
            The description of a the Token parameter.
     
        .PARAMETER Company
            The description of a the Company parameter.
     
        .EXAMPLE
            PS C:\> set-WITsieTokenstore -Token 'One value' -Company 32
            'This is the output'
            This example shows how to call the set-WITsieTokenstore function with named parameters.
     
        .EXAMPLE
            PS C:\> set-WITsieTokenstore 'One value' 32
            'This is the output'
            This example shows how to call the set-WITsieTokenstore function with positional parameters.
     
        .INPUTS
            System.String,System.Int32
     
        .OUTPUTS
            System.String
     
        .NOTES
            For more information about advanced functions, call Get-Help with any
            of the topics in the links listed below.
     
        .LINK
            about_functions_advanced
     
        .LINK
            about_comment_based_help
     
        .LINK
            about_functions_advanced_parameters
     
        .LINK
            about_functions_advanced_methods
    #>

    function set-WITsieTokenstore {
        [CmdletBinding()]
        param(
            [Parameter(Position=0, Mandatory=$true)]
            $Token,
            [Parameter(Position=1)]
            $Company
        )
        begin {
            try {
            }
            catch {
            }
        }
        process {
            try
            {
                $Work = $Token.split('-')
                $enc=$work[2]
                $E_2 = [convert]::toint64($enc, 16)
                
                
            }
            catch {
            }
        }
        end {
            try {
            }
            catch {
            }
        }
    }
    
    
    #get-witsietoken -Integration_user_API_code '6f38c262-ec66-df5e-3354-18dc3847ee47'
    
    #get-WITsie -Token 'e038e337-0fe5-4a16-bb03-17da2c0c8289'
    
    $fiscal = get-WITsieFiscalyears -Token '34da2b26-3646-4d25-a0a2-6c0ecf3c1b87'
    $data=get-WITsie -Token '34da2b26-3646-4d25-a0a2-6c0ecf3c1b87' -fiscalyear $fiscal[0].id
    
    
    
    #$enc = [System.Text.Encoding]::GetEncoding(850)
    #$bytes=$data.tobyte()
    
    #$text = $enc.GetString($bytes)
    
    #$sie = $text.Split([Environment]::NewLine)
    
    
    #$enc = [System.Text.Encoding]::UTF8.GetBytes($data)
    #[System.Text.Encoding]::UTF8.GetString($enc)
    
    
    # 34da2b26-3646-4d25-a0a2-6c0ecf3c1b87 BrickTerra
    
    
    
}
#endregion Source: Test.ps1

#region Source: newcustomer.ps1
function Invoke-newcustomer_ps1
{
    $sqlserver='d-witgum-s1'
    $Siedatabasename='Sie'
    <#
    .Synopsis
       Skapar en ny guid med eller utan {}
    .DESCRIPTION
       $Without Switch som tarbort {} om guid
     
    .EXAMPLE
       new-WITguid
    .EXAMPLE
       new-WITguid -without
    #>

    Function New-WITguid
      {
        [CmdletBinding()]
        Param
        (
           [Switch]$Without
    
        )
    
      
      $temp=[guid]::NewGuid().guid
    
      if ($Without -eq $true)
        {
          return "$temp"
        } else {
          return "{$temp}"
        }
      }
    #############################################################################
    #
    
    <#
    .Synopsis
       Öppnar ett recordset med data
    .DESCRIPTION
       $dbconn Koppling till db
       $Table Vilken tabell behövs ej vid query
       $Query Använd denna fråga istället för en byggd
       $where Where sats ger "Select * FROM [dbo].[$table] where $where"
       $all Switch Ger "Select * FROM [dbo].[$table]"
        
     
       Utan query och Where och all ger "Select top(0) * FROM [dbo].[$table]"
     
    .EXAMPLE
       Example of how to use this cmdlet
    .EXAMPLE
       Another example of how to use this cmdlet
    #>

    function connect-WITsqltable
    {
        [CmdletBinding()]
        [Alias()]
        
        Param
        (
            # Param1 help description
            [Parameter(Mandatory=$true,
                       ValueFromPipelineByPropertyName=$true,
                       Position=0)]
            $dbconn,
            $Table,
            $Query,
            $where,
            
            [Switch]$all
    
        )
    
        Begin
        {
        }
        Process
        {
        $rset = new-object -comobject ADODB.Recordset;
        $rset.CursorLocation=3
        if ($all) 
           {
           $query1="Select * FROM [dbo].[$table]"
           }
        elseif ($Query.Length -gt 1)
           {
           $query1=$query
           }
        elseif ($Where.Length -gt 1)
           {
           $query1="Select * FROM [dbo].[$table] where $where"
           }
        else
           {
           $query1="Select top(0) * FROM [dbo].[$table]"
           }
     
       
    
        $open=$rset.open($query1, $dbConn,2,4);
        
        
        }
        End
        {
        return $rset
        }
    }
    
    <#
    .Synopsis
       Updaterar eller lägger till en post skapad av objektet
    .DESCRIPTION
      $Object Med de fält som ska kolla om de ändrats
      $Recordset Det filtrerade recordsetet med posten som ska ändras eller skapas
      $IDguidfieldname Nyckel guid fält namn
      $Skipfields Sträng med Fältnamn komma separerade
      Returnerar Status 'New eller Changed eller Same' och IDguid
    .EXAMPLE
       Example of how to use this cmdlet
    .EXAMPLE
       Another example of how to use this cmdlet
    #>

    class WITsqlrecordstate
    {
    [string]$State
    [string]$Guid
    }
    
    function Update-WITsqlrecord
    {
        [CmdletBinding()]
        [Alias()]
        
        Param
        (
            # Param1 help description
            [Parameter(Mandatory=$true,
                       ValueFromPipelineByPropertyName=$true,
                       Position=0)]
            $Object,
            [Parameter(Mandatory=$true,
                       ValueFromPipelineByPropertyName=$true,
                       Position=1)]
            $Recordset,
            [Parameter(Mandatory=$true,
                       ValueFromPipelineByPropertyName=$true,
                       Position=2)]
            $IDguidfieldname,
            $Skipfields,
            [Switch]$newpost
        )
    
        Begin
        {
        }
        Process
        {
        if ($Recordset.eof -eq $true -or $newpost) 
           {
           $F_Changed=$true
           $F_New=$true
           $Recordset.addnew()
           $Recordset.Fields.Item($IDguidfieldname).Value=New-WITguid
           $f_guid=$Recordset.Fields.Item($IDguidfieldname).Value
           } 
        else 
           {
           $F_Changed=$false
           $F_New=$false
           
           }
        $fields=$Object|Get-Member | where membertype -like '*Property' | select -ExpandProperty name
        foreach($field_name in $fields)
          {
          if ("$Skipfields," -notlike  "*$field_name,*") 
             {
             $objectvalue=[string]$Object.$field_name
             if ($objectvalue -eq $null) {$objectvalue=''}
             if ($Recordset.Fields.Item($field_name).Value -ne $objectvalue) 
                {
                if ($F_Changed -eq $false) 
                   {
                   $Recordset.editmode()
                   $F_Changed=$true
                   $f_guid=$Recordset.Fields.Item($IDguidfieldname).Value
                   }
                $Recordset.Fields.Item($field_name).Value=$objectvalue
                }
             else
                {
             
                }
             }
          } #for fields
        } #Process
        End
        {
        if ($F_New -eq $true) 
           {
           $state='New'
           }
        elseif ($F_Changed -eq $true)
            {
            $state='Changed'
            }
        else
            {
            $f_guid=$Recordset.Fields.Item($IDguidfieldname).Value
            $state='Same'
            }
        $recordstate=[WITsqlrecordstate]::new()
        $recordstate.Guid=$f_guid
        $recordstate.State=$state
        return $recordstate
        }
    }
    
    <#
    .Synopsis
       Updaterar eller lägger till en post skapad av objektet
    .DESCRIPTION
      $Object Med de fält som ska kolla om de ändrats
      $Recordset Det filtrerade recordsetet med posten som ska ändras eller skapas
      $IDguidfieldname Nyckel guid fält namn
      $Skipfields Sträng med Fältnamn komma separerade
      Returnerar Status 'New eller Changed eller Same' och IDguid
    .EXAMPLE
       Example of how to use this cmdlet
    .EXAMPLE
       Another example of how to use this cmdlet
    #>

    
    
    
    <#
    .Synopsis
       Skapar ett dbconn objekt mot databasen
    .DESCRIPTION
       $sqlserver
       $database
    .EXAMPLE
       Example of how to use this cmdlet
    .EXAMPLE
       Another example of how to use this cmdlet
    #>

    function new-WITsqlconnection
    {
        [CmdletBinding()]
        [Alias()]
        [OutputType([int])]
        Param
        (
            # Param1 help description
            [Parameter(Mandatory=$true,
                       ValueFromPipelineByPropertyName=$true,
                       Position=0)]
            $sqlserver,
            [Parameter(Mandatory=$true,
                       ValueFromPipelineByPropertyName=$true,
                       Position=1)]
            $database,
            $username,
            $password
        )
    
        Begin
        {
        #Provider=SQLOLEDB;
        #Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
    #Öppna dataanslutningen
    $dbConn = new-object -comobject ADODB.Connection;
    if ($username -eq $null) 
       {
         $connect = "Provider=SQLOLEDB;Server=$sqlserver;Database=$database;Integrated Security=SSPI;";  # ConnectionString
       } else {
         $connect = "Provider=SQLOLEDB;Server=$sqlserver;Database=$database;User Id=$username;Password=$password;";  # ConnectionString
       }
    $dbConn.Open($connect); # öppna anslutning
    $dbConn.CursorLocation = 3  # 3= Client cursor mode
        }
        Process
        {
        return $dbConn
        }
        End
        {
        }
    }
    
    
    
    
    
    $db = new-WITsqlconnection -sqlserver $sqlserver -database $Siedatabasename -username 'bw' -password 'bw&98&BW'
    #new-WITsiecustomer -Integration_user_code 063852a6-a333-5afc-60f2-756102550baa -Token_DB $db
    new-WITsiecustomer -Integration_user_code 42d4bda4-15fa-76a8-c0d8-efacf72531bf -Token_DB $db
    new-WITsiecustomer -Integration_user_code f962f7fb-282e-dd04-433d-38fa7d95c3c9 -Token_DB $db
    new-WITsiecustomer -Integration_user_code 05a75585-25a2-5a01-4a64-6c656847d3bb -Token_DB $db
    new-WITsiecustomer -Integration_user_code 1cb4539c-ac97-d794-82c8-7e37f7c38fe9 -Token_DB $db
    new-WITsiecustomer -Integration_user_code f696a4e7-a895-fba9-1adb-64e1f494f8b1 -Token_DB $db
    new-WITsiecustomer -Integration_user_code e826a96a-a00b-1125-bb08-cef11d8e0154 -Token_DB $db
    new-WITsiecustomer -Integration_user_code e04a3095-c3eb-5430-502a-f127d862eaad -Token_DB $db
    new-WITsiecustomer -Integration_user_code 56078e4a-4ba5-9064-4865-0c5722327930 -Token_DB $db
    new-WITsiecustomer -Integration_user_code 0ffcf250-1a3d-c39b-ba37-3c35d2efb6a4 -Token_DB $db
    new-WITsiecustomer -Integration_user_code ef1d3900-aceb-d2f9-bfcc-32bdd2a1417a -Token_DB $db
    
}
#endregion Source: newcustomer.ps1

#region Source: siefunctions.ps1
function Invoke-siefunctions_ps1
{
    <#
        .NOTES
        ===========================================================================
         Created with: SAPIEN Technologies, Inc., PowerShell Studio 2021 v5.8.191
         Created on: 2021-09-22 14:50
         Created by: Björn Willim
         Organization: Witcon AB
         Filename: Siefunktions.ps1
        ===========================================================================
        .DESCRIPTION
            A description of the file.
    #>

    
    
    
    <#
        .NOTES
        ===========================================================================
         Created with: SAPIEN Technologies, Inc., PowerShell Studio 2021 v5.8.191
         Created on: 2021-09-06 11:01
         Created by: Björn Willim
         Organization: Witcon AB
         Filename: Test.ps1
        ===========================================================================
        .DESCRIPTION
            A description of the file.
    #>

    function get-WITsieToken
    {
        [CmdletBinding()]
        param (
            [Parameter(Position = 0, Mandatory = $true)]
            $Integration_user_API_code
        )
        begin
        {
            try
            {
            }
            catch
            {
            }
        }
        process
        {
            try
            {
                $ClientSecret = 'wa5zIksMZ6'
                $Params = @{
                    "Uri"    = 'https://api.fortnox.se/3/sie/4?financialyear=1'
                    #"Uri" ="https://apps.fortnox.se/oauth-v1/token"
                    "Method" = 'GET'
                    "Header" = @{
                        "Authorization-Code" = $Integration_user_API_code
                        "Client-Secret"         = $ClientSecret
                        "Content-Type"         = "application/json"
                        "Accept"             = "application/json"
                    }
                    "Body"   = @{ }
                }
                
                $token = Invoke-RestMethod @Params
                $token.Authorization.AccessToken
                Write-Host "Token fetched "
            }
            catch
            {
                Write-Error "Could not fetch Token"
            }
        }
        end
        {
            try
            {
            }
            catch
            {
            }
        }
    }
    #
    <#
        .SYNOPSIS
            A brief description of the get-WITsie function.
     
        .DESCRIPTION
            A detailed description of the get-WITsie function.
     
        .PARAMETER Token
            The description of a the ParameterA parameter.
     
        .PARAMETER ParameterB
            The description of a the ParameterB parameter.
     
        .EXAMPLE
            PS C:\> get-WITsie -ParameterA 'One value' -ParameterB 32
            'This is the output'
            This example shows how to call the get-WITsie function with named parameters.
     
        .EXAMPLE
            PS C:\> get-WITsie 'One value' 32
            'This is the output'
            This example shows how to call the get-WITsie function with positional parameters.
     
        .INPUTS
            System.String,System.Int32
     
        .OUTPUTS
            System.String
     
        .NOTES
            For more information about advanced functions, call Get-Help with any
            of the topics in the links listed below.
     
        .LINK
            about_functions_advanced
     
        .LINK
            about_comment_based_help
     
        .LINK
            about_functions_advanced_parameters
     
        .LINK
            about_functions_advanced_methods
    #>

    function get-WITsiedata
    {
        [CmdletBinding()]
        param (
            [Parameter(Position = 0, Mandatory = $true)]
            $Token,
            [Parameter(Position = 1, Mandatory = $true)]
            $Fiscalyear)
        begin
        {
            try
            {
            }
            catch
            {
            }
        }
        process
        {
            try
            {
                $ClientSecret = 'wa5zIksMZ6'
                $Params = @{
                    "Uri" = "https://api.fortnox.se/3/sie/4?financialyear=$fiscalyear "
                    "Method" = 'GET'
                    "Header" = @{
                        "Access-Token"  = $token
                        "Client-Secret" = $ClientSecret
                        "Content-Type"  = "application/json"
                        "Accept"        = "application/json"
                    }
                    "Body" = @{ }
                    
                }
                
                
                $b = Invoke-WebRequest @Params
                $enc = [System.Text.Encoding]::GetEncoding(850)
                $text = $enc.GetString($b.Content)
                $text.Split([Environment]::NewLine)
            }
            catch
            {
            }
        }
        end
        {
            try
            {
            }
            catch
            {
            }
        }
    }
    
    function get-WITsieFiscalyears
    {
        [CmdletBinding()]
        param (
            [Parameter(Position = 0, Mandatory = $true)]
            $Token
        )
        begin
        {
            try
            {
            }
            catch
            {
            }
        }
        process
        {
            try
            {
                $ClientSecret = 'wa5zIksMZ6'
                $Params = @{
                    "Uri"    = 'https://api.fortnox.se/3/financialyears'
                    "Method" = 'GET'
                    "Header" = @{
                        "Access-Token"  = $token
                        "Client-Secret" = $ClientSecret
                        "Content-Type"  = "application/json"
                        "Accept"        = "application/json"
                    }
                    "Body"   = @{ }
                    
                }
                
                
                $b = Invoke-WebRequest @Params
                $text = convertfrom-json ($b.Content)
                $text.FinancialYears
                
            }
            catch
            {
            }
        }
        end
        {
            try
            {
            }
            catch
            {
            }
        }
    }
    
    <#
        .SYNOPSIS
            A brief description of the set-WITsieTokenstore function.
     
        .DESCRIPTION
            A detailed description of the set-WITsieTokenstore function.
     
        .PARAMETER Token
            The description of a the Token parameter.
     
        .PARAMETER Company
            The description of a the Company parameter.
     
        .EXAMPLE
            PS C:\> set-WITsieTokenstore -Token 'One value' -Company 32
            'This is the output'
            This example shows how to call the set-WITsieTokenstore function with named parameters.
     
        .EXAMPLE
            PS C:\> set-WITsieTokenstore 'One value' 32
            'This is the output'
            This example shows how to call the set-WITsieTokenstore function with positional parameters.
     
        .INPUTS
            System.String,System.Int32
     
        .OUTPUTS
            System.String
     
        .NOTES
            For more information about advanced functions, call Get-Help with any
            of the topics in the links listed below.
     
        .LINK
            about_functions_advanced
     
        .LINK
            about_comment_based_help
     
        .LINK
            about_functions_advanced_parameters
     
        .LINK
            about_functions_advanced_methods
    #>

    function set-WITsieTokenstore
    {
        [CmdletBinding()]
        param (
            [Parameter(Position = 0, Mandatory = $true)]
            $Token,
            [Parameter(Position = 1)]
            $Company
        )
        begin
        {
            try
            {
            }
            catch
            {
            }
        }
        process
        {
            try
            {
                $Work = $Token.split('-')
                $enc = $work[2]
                $E_2 = [convert]::toint64($enc, 16)
                
                
            }
            catch
            {
            }
        }
        end
        {
            try
            {
            }
            catch
            {
            }
        }
    }
    
    
    
    <#
    .Synopsis
       Short description
    .DESCRIPTION
       Long description
    .EXAMPLE
       Example of how to use this cmdlet
    .EXAMPLE
       Another example of how to use this cmdlet
    #>

    function get-WITsieRowdata
    {
        [CmdletBinding()]
        [Alias()]
        Param
        (
            # Param1 help description
            [Parameter(Mandatory = $true,
                       ValueFromPipelineByPropertyName = $true,
                       Position = 0)]
            $Sierow
        )
        
        
        Process
        {
            #$pos=$Sierow.indexof(" ")
            #$command=$Sierow.substring(0,$pos)
            #$data=$Sierow.substring($pos+1)
            $string = $false
            $string2 = $false
            $word = ""
            $workdata = ""
            $wordindexes = @()
            $data = $Sierow
            for ($i = 0; $i -lt $data.length; $i++)
            {
                #$data[$i]
                if ($data[$i] -eq ' ' -and $string -eq $false -and $string2 -eq $false)
                {
                    $wordindexes += $workdata
                    $workdata = ""
                }
                else
                {
                    if ($data[$i] -eq '"')
                    {
                        $string = $true
                    }
                    else
                    {
                        if ($string -eq $true)
                        {
                            if ($data[$i] -eq '"')
                            {
                                $string = $false
                            }
                            else
                            {
                                $workdata += $data[$i]
                            }
                        }
                        else
                        {
                            $workdata += $data[$i]
                        }
                    }
                    
                    
                    
                }
            } #For
            $wordindexes += $workdata
            
        } # Progress
        
        End
        {
            $wordindexes
        }
    }
    
    class WITsiefile
    {
        [string]$SoftwareProduct_name
        [string]$SoftwareProduct_version
        [string]$FileCreation_time
        [string]$FileCreation_by
        [string]$Filename
        [string]$AccountingCurrency_currency
        [string]$Sietype
        [string]$Format
        [string]$Filenr
        [string]$Rar0
        [string]$Rar1
        [string]$KRTYP
        [string]$Omfattn
        [string]$CompanyGuid
        [string]$Guid
    }
    
    class WITsie
    { }
    class WITsiedata
    {
        [INT]$row
        [string]$Command
        [string]$D1
        [string]$D2
        [string]$D3
        [string]$D4
        [string]$D5
        [string]$D6
        [string]$D7
        [string]$D8
        [string]$D9
        [string]$D10
    }
    
    function Get-WITsieDecodeToken
    {
        [CmdletBinding()]
        param
        (
            [Parameter(Mandatory = $true,
                       Position = 0)]
            $crypttoken
        )
        $temp1 = $crypttoken.length - 37
        $token1 = $crypttoken.substring(0, $temp1)
        $token1
    }
    
    function Get-WITsieencodeToken
    {
        [CmdletBinding()]
        param
        (
            [Parameter(Mandatory = $true,
                       Position = 0)]
            $token
        )
        
        $code = New-Guid | select -ExpandProperty Guid
        $code1 = $token + "-" + $code
        $code1
    
    }
    
    function new-WITsiecustomer
    {
        param (
            [Parameter(Mandatory = $true, Position = 0)]
            $Integration_user_code,
    [Parameter(Mandatory = $true, Position = 1)]
            $Token_DB
        )
        try {
        $dbTokenset = connect-WITsqltable -dbconn $Token_DB -Table 'token' -all
        $newtoken = get-WITsieToken -Integration_user_API_code $Integration_user_code
        $crypt = Get-WITsieencodeToken -token $newtoken
        $work = new-object -TypeName witsie
        $work | add-member token $crypt
        Write-host $newtoken
        write-host $crypt
        $status = Update-WITsqlrecord -Object $work -Recordset $dbTokenset -IDguidfieldname guid -newpost
        $dbTokenset.update()
        $dbTokenset.updatebatch()
        $dbTokenset.close()
        $status
        }
        catch
        {
            $witerr = new-object -TypeName witsie
            $witerr | add-member token $crypt
            $witerr | Add-Member error $error[0].Exception
            $witerr | Add-Member Token_db $Token_db
            $witerr |Add-Member Status $status
                    
            Write-host $newtoken
            
            return $witerr
            
        }
        
    }
    
    function convert-WITsiedata {
    param(
    # Param1 help description
            [Parameter(Mandatory = $true,
                       ValueFromPipelineByPropertyName = $true,
                       Position = 0)]
            $Sie
    )
    $global:sieloop=0
    $global:vernr=''
    $global:verserie=''
    $data=@()
    while ($global:sieloop -le $sie.Count)
    {
    $workrow=$sie[$global:sieloop]
    #write-host $global:sieloop $workrow
     if ($workrow.length -ge 2  ) {
    $siepost=New-Object -TypeName Witsiedata
    $pattern='(?<=\#).+?(?=\ )'
    $command=[regex]::Matches($workrow, $pattern).Value
    switch ($command)
    {
        'OBJEKT' {
       # $tmp1=$workrow.split('"')
       # $tmp2=$tmp1[0].split(' ')
       # $pattern='(?<=\ ").+?(?=\")'
       # $pattern='((?<=\#).+?(?=\ )) ((?<=\ ).+?(?=\ )) ((?=").+?(?=\").+?) ((?=").+?(?=\").+?)'
        $pattern='((?<=\ ).+?(?=\ )).((?=").+?(?=\").+?) ((?=").+?(?=\").+?)'
        $tmp3=[regex]::split($workrow, $pattern)
        $siepost.row=$global:sieloop
        $siepost.command=$command
        $siepost.d1=$tmp3[1].Replace(' ','')
        $siepost.d2=$tmp3[2].Replace('"','')
        $siepost.d3=$tmp3[3].Replace('"','')
        $siepost
        }
          'DIM' {
       # $tmp1=$workrow.split('"')
       # $tmp2=$tmp1[0].split(' ')
       # $pattern='(?<=\ ").+?(?=\")'
       # $pattern='((?<=\#).+?(?=\ )) ((?<=\ ).+?(?=\ )) ((?=").+?(?=\").+?) ((?=").+?(?=\").+?)'
        $pattern='((?=\ ).+?(?=\ )).((?=").+?(?=\").+?)'
        $tmp3=[regex]::split($workrow, $pattern)
        $siepost.row=$global:sieloop
        $siepost.command=$command
        $siepost.d1=$tmp3[1].Replace(' ','')
        $siepost.d2=$tmp3[2].Replace('"','')
        $siepost
        }
        'FNAMN' {
        $pattern='((?<= ").+?(?=\"))'
        $tmp3=[regex]::match($workrow, $pattern).value
        $siepost.row=$global:sieloop
        $siepost.command=$command
        $siepost.d1=$tmp3
        $siepost
        }
        'GEN' {
       # $tmp1=$workrow.split('"')
       # $tmp2=$tmp1[0].split(' ')
       # $pattern='(?<=\ ").+?(?=\")'
       # $pattern='((?<=\#).+?(?=\ )) ((?<=\ ).+?(?=\ )) ((?=").+?(?=\").+?) ((?=").+?(?=\").+?)'
        $pattern='((?=\ ).+?(?=\ )).((?=").+?(?=\").+?)'
        $tmp3=[regex]::split($workrow, $pattern)
        $siepost.row=$global:sieloop
        $siepost.command=$command
        $siepost.d1=$tmp3[1].Replace(' ','')
        $siepost.d2=$tmp3[2].Replace('"','')
        $siepost
        }
       
         'KONTO' {
       # $tmp1=$workrow.split('"')
       # $tmp2=$tmp1[0].split(' ')
       # $pattern='(?<=\ ").+?(?=\")'
       # $pattern='((?<=\#).+?(?=\ )) ((?<=\ ).+?(?=\ )) ((?=").+?(?=\").+?) ((?=").+?(?=\").+?)'
        $pattern='((?=\ ).+?(?=\ )).((?=").+?(?=\").+?)'
        $tmp3=[regex]::split($workrow, $pattern)
        $siepost.row=$global:sieloop
        $siepost.command=$command
        $siepost.d1=$tmp3[1].Replace(' ','')
        $siepost.d2=$tmp3[2].Replace('"','')
        $siepost
        }
        {$_ -in 'FNAMN','FNR'} {
        $pattern='((?<= ").+?(?=\"))'
        $tmp3=[regex]::match($workrow, $pattern).value
        $siepost.row=$global:sieloop
        $siepost.command=$command
        $siepost.d1=$tmp3
        $siepost
        }
    
    
    
        {$_ -in 'TRANS','BTRANS','RTRANS'} {
        $tmp1=$workrow.split('{')
        $tmp2=$tmp1[0].split(' ')
        $pattern='(?<=\ {).+?(?=\})'
        $tmp3=[regex]::Matches($workrow, $pattern).Value
        $tmp4=$workrow.split('}')
        $tmp5=$tmp4[1].split(' ')
        $pattern='(?<=\ ").+?(?=\")'
        $tmp6=[regex]::Matches($tmp5, $pattern).Value
    
        $siepost.row=$global:sieloop
        $siepost.command=$command
        $siepost.d1=$tmp2[1]
        $siepost.d2=$tmp3
        $siepost.d3=$tmp5[1]
        $siepost.d4=$tmp5[2]
        $siepost.d5=$tmp6
        $siepost.d9=$global:verserie
        $siepost.d10=$global:vernr
        $siepost
    
        }
        'VER' {
        $pattern='((?<=\#).+?(?=\ )) ((?<=\ ).+?(?=\ )) ((?=").+?(?=\"))(.+) ((?=").+?(?=\").+?)(.+)'
        $tmp3=[regex]::split($workrow, $pattern)
        $global:verserie=$tmp3[2].replace('"','')
        $global:vernr=$tmp3[3].replace('"','')
        $siepost.row=$global:sieloop
        $siepost.command=$command
        $siepost.d1=$global:verserie
        $siepost.d2=$global:vernr
        $siepost.d3=$tmp3[4].replace('"','').replace(' ','')
        $siepost.d4=$tmp3[5].replace('"','')
        $siepost.d5=$tmp3[6].replace(' ','')
        $siepost.d6=$tmp3[7]
        $siepost.d7=$tmp3[8]
        
        $siepost
        }
    
        Default { # $pattern='((?=\ ).+?(?=\ )).((?=").+?(?=\").+?)'
       
        $tmp3=$workrow.split(' ')
        $siepost.row=$global:sieloop
        $siepost.command=$command
        $siepost.d1=$tmp3[1]
        $siepost.d2=$tmp3[2]
        $siepost.d3=$tmp3[3]
        $siepost.d4=$tmp3[4]
        $siepost.d5=$tmp3[5]
        $siepost.d6=$tmp3[6]
        $siepost.d7=$tmp3[7]
        $siepost.d8=$tmp3[8]
        $siepost
        
        }
    
    }
    
    $data+=$siepost
    }
    #$workrow.IndexOf('"')
    
    #$pattern='(?<=\ ").+?(?=\")'
    
    
    #if () {}
    $global:sieloop++
    }
    
    $data
    }
    
}
#endregion Source: siefunctions.ps1

#region Source: Sieimport.ps1
function Invoke-Sieimport_ps1
{
    $sqlserver='192.168.48.14'
    $Siedatabasename='Sie'
    $file= 'C:\Data\Fågelnssamfällighetsförening20201204_114359.se'
    $siefolder='\\d-witgum-ts1\c$\Users\Public\Documents\Digum SNB\SIE-4 filer 201231 v210315'
    
    #############################################################################
    #
    
    
    
    $db = new-WITsqlconnection -sqlserver $sqlserver -database $Siedatabasename -username 'bw' -password 'bw&98&BW'
    $Tokenset = connect-WITsqltable -dbconn $db -Table 'token' -all
    $tokens = @()
    $Tokenset.movefirst()
    while (-not $Tokenset.eof)
    {
        
    ## foreach ($FILE IN $FILES) {
    $tok=Get-WITsieDecodeToken -crypttoken $Tokenset.Fields.Item("Token").value
    $fiscal = get-WITsieFiscalyears -Token $tok
    $data=get-WITsiedata -Token $tok -fiscalyear $fiscal[0].id
    $temp=$fiscal[0].FromDate
    Write-host "Hämtat data från $temp"
    
    
    $Filetable=connect-WITsqltable -dbconn $db -Table 'fileinfo' -all
    $Companytable=connect-WITsqltable -dbconn $db -Table 'Company' -all
    
    $Fiscaltable=connect-WITsqltable -dbconn $db -Table 'CompanyFiscalYears' -all
    
    
    $sieraw=$data.Split([Environment]::NewLine)
    
    $siedata=@()
    <#
    $siecnt=1
     
    $sie|% {
    $siepost=[WITsiedata]::new()
     $row=get-WITsierowdata -Sierow $_
     $siepost.row=$siecnt
     $siepost.Command=$row[0]
     Write-host $siecnt
     for ($i = 1; $i -le $row.Count;$i++)
    {
    $d="d$i"
    $siepost.$d=$row[$i]
     
     
    }
    if ($row.count -ge 2)
    {
     $siedata+=$siepost
     }
     
    $siecnt++
    }
     
    #>

    $siedata+=convert-WITsiedata -Sie $sieraw
    
    $fnr=$siedata|where Command -eq '#FNR'|select -ExpandProperty D1
    $GEN=$siedata|where Command -eq '#GEN'|select -ExpandProperty D1
    $Fnamn=$siedata|where Command -eq '#Fnamn'|select -ExpandProperty D1
    $SIETYP=$siedata|where Command -eq '#SIETYPE'|select -ExpandProperty D1
    $orgnr=$siedata|where Command -eq '#ORGNR'|select -ExpandProperty D1
    $ib0startdate=$siedata|where Command -eq '#RAR' |where D1 -eq '0'|select -ExpandProperty D2
    $ib0stopdate=$siedata |where Command -eq '#RAR' |where D1 -eq '0'|select -ExpandProperty D3
    $ib1startdate=$siedata|where Command -eq '#RAR' |where D1 -eq '-1'|select -ExpandProperty D2
    $ib1stopdate=$siedata |where Command -eq '#RAR' |where D1 -eq '-1'|select -ExpandProperty D3
    
    $Companytable.filter="OrganizationID = '$Orgnr'"
    $Newpost= New-Object -TypeName 'Witsie' 
    $newpost|Add-Member OrganizationID $orgnr
    $Newpost|Add-Member Name $Fnamn
    $stat=Update-WITsqlrecord -Recordset $Companytable -IDguidfieldname 'Guid' -Object $Newpost 
    $Companytable.Update()
    $Companytable.UpdateBatch()
    $Companytable.close()
    $Companyguid=$stat.Guid
    $Filetable.filter="RAR0Startdate = $ib0startdate and RAR0Stopdate = $ib0stopdate and CompanyGuid = $companyguid"
     
    $filepost= New-Object -TypeName 'Witsie' 
    $filepost|Add-Member FileNR $FNR
    $filepost|Add-Member Filename $file
    $filepost|Add-Member Companyguid $Companyguid
    $filepost|Add-Member RAR0Startdate $ib0startdate
    $filepost|Add-Member RAR0Stopdate $ib0stopdate
    $stat=Update-WITsqlrecord -Recordset $Filetable -IDguidfieldname 'Guid' -Object $filepost 
    $Filetable.Update()
    $Filetable.UpdateBatch()
    $Filetable.close()
    $fileguid=$stat.Guid
    
    Write-host "$Fnamn $orgnr Online 0 Startdatum $ib0startdate"
    
    #############################
    
    $sieKonton=$siedata|where Command -eq '#Konto' 
    Write-Host "Accounts"
    $sql="delete from Accounts where Fileinfoguid='$Fileguid'"
    $query=connect-WITsqltable -dbconn $db  -Query $sql 
    $Accountstable=connect-WITsqltable -dbconn $db -Table 'Accounts' -where "Fileinfoguid='$fileguid'"
    foreach($konto in $sieKonton)
      {
      $newpost= New-Object -TypeName 'Witsie' 
      $newpost|Add-Member FileinfoGuid $fileguid
      $newpost|Add-Member Account_id $konto.d1
      $newpost|Add-Member Account_Name $konto.d2
      $stat=Update-WITsqlrecord -Recordset $Accountstable -IDguidfieldname 'Guid' -Object $newpost -newpost
      }
    $Accountstable.Update()
    $Accountstable.UpdateBatch()
    #$Accountstable.Close()
    #####################
    
    Write-Host "Accounts SRU"
    $sieKonton=$siedata|where Command -eq '#SRU'
    #$Accountstable=connect-WITsqltable -dbconn $db -Table 'Accounts'
    foreach($konto in $sieKonton)
      {
      $kontosru=$konto.D1
      $Accountstable.filter="Account_id='$kontosru'"
      $newpost= New-Object -TypeName 'Witsie' 
      [String]$srukonto=$konto.D2
      $newpost|Add-Member SRU $srukonto
      $stat=Update-WITsqlrecord -Recordset $Accountstable -IDguidfieldname 'Guid' -Object $newpost
      $Accountstable.Update()
      $Accountstable.UpdateBatch()
      }
    
      
    
    #############################
    
    $sql="delete from Account_entries where Fileinfoguid='$Fileguid'"
    $query=connect-WITsqltable -dbconn $db  -Query $sql 
    $Accountstable=connect-WITsqltable -dbconn $db -Table 'Account_entries' #-where "Fileinfoguid='$fileguid'"
    
    Write-Host "ib"
    
    $sieKonton=$siedata|where Command -eq '#IB' 
    foreach($konto in $sieKonton)
      {
      $newpost= New-Object -TypeName 'Witsie' 
      $newpost|Add-Member FileinfoGuid $fileguid
      if ($konto.D1 -eq '0') 
         {
         $siedate=$ib0startdate
         } elseif ($konto.D1 -eq '-1')
            {
            $siedate=$ib1startdate
            }
      $siemonth=$siedate.Substring(0,4)+"00"
      $newpost|Add-Member Account_id $konto.d2
      $newpost|Add-Member Date $siedate
      $newpost|Add-Member Type "IB"
      $newpost|Add-Member Month $siemonth
      $newpost|Add-Member amount $konto.D3
      $newpost|Add-Member quantity $konto.D4
      $newpost|Add-Member yearno $konto.D1
      $stat=Update-WITsqlrecord -Recordset $Accountstable -IDguidfieldname 'Guid' -Object $newpost -newpost
      }
    
      Write-Host "Ub"
    $sieKonton=$siedata|where Command -eq '#UB' 
    foreach($konto in $sieKonton)
      {
      $newpost= New-Object -TypeName 'Witsie' 
      $newpost|Add-Member FileinfoGuid $fileguid
      if ($konto.D1 -eq '0') 
         {
         $siedate=$ib0stopdate
         } elseif ($konto.D1 -eq '-1')
            {
            $siedate=$ib1stopdate
            }
       $siemonth=$siedate.Substring(0,4)+"13"
      $newpost|Add-Member Account_id $konto.d2
      $newpost|Add-Member Date $siedate
      $newpost|Add-Member Type "UB"
      $newpost|Add-Member Month $siemonth
      $newpost|Add-Member amount $konto.D3
      $newpost|Add-Member quantity $konto.D4
      $newpost|Add-Member yearno $konto.D1
      $stat=Update-WITsqlrecord -Recordset $Accountstable -IDguidfieldname 'Guid' -Object $newpost -newpost
      }
    
    $sieKonton=$siedata|where Command -eq '#RES' 
    foreach($konto in $sieKonton)
      {
      $newpost= New-Object -TypeName 'Witsie' 
      $newpost|Add-Member FileinfoGuid $fileguid
      if ($konto.D1 -eq '0') 
         {
         $siedate=$ib0stopdate    
         } elseif ($konto.D1 -eq '-1')
            {
            $siedate=$ib1stopdate
            }
    
      $newpost|Add-Member Account_id $konto.d2
      $newpost|Add-Member Date $siedate
      $newpost|Add-Member Type "RES"
      $newpost|Add-Member amount $konto.D3
      $newpost|Add-Member quantity $konto.D4
      $newpost|Add-Member yearno $konto.D1
      $stat=Update-WITsqlrecord -Recordset $Accountstable -IDguidfieldname 'Guid' -Object $newpost -newpost
      }
      Write-Host "Psaldo"
      $sieKonton=$siedata|where Command -eq '#PSALDO' 
    foreach($konto in $sieKonton)
      {
      $newpost= New-Object -TypeName 'Witsie' 
      $newpost|Add-Member FileinfoGuid $fileguid
      if ($konto.D1 -eq '0') 
         {
         $siedate=$ib0startdate    
         } elseif ($konto.D1 -eq '-1')
            {
            $siedate=$ib1startdate
            }
    
      $newpost|Add-Member Account_id $konto.d3
      $newpost|Add-Member Date $siedate
      $newpost|Add-Member Month $konto.d2
      $newpost|Add-Member Type "PSALDO"
      $newpost|Add-Member amount $konto.D5
      $newpost|Add-Member quantity $konto.d6
      $newpost|Add-Member yearno $konto.D1
      $stat=Update-WITsqlrecord -Recordset $Accountstable -IDguidfieldname 'Guid' -Object $newpost -newpost
      }
    
      ###########################################################################################
      $sql="delete from Verifications where Fileinfoguid='$Fileguid'"
    $query=connect-WITsqltable -dbconn $db  -Query $sql 
    $Ver_table=connect-WITsqltable -dbconn $db -Table 'Verifications' #-where "Fileinfoguid='$fileguid'"
    $sql="delete from Verifications_entries where Fileinfoguid='$Fileguid'"
    $query=connect-WITsqltable -dbconn $db  -Query $sql 
    $Ver_entries_table=connect-WITsqltable -dbconn $db -Table 'Verifications_entries' #-where "Fileinfoguid='$fileguid'"
    
    Write-Host "Verifications"
    
      $siever=$siedata|where Command -eq '#Ver' 
      [int]$siefirtsverrow=$siever[0].row
      
      $siekonton=$siedata|where row -ge $siefirtsverrow
      
      $ver_guid=""
    foreach($konto in $sieKonton)
      {
      if ($konto.Command -eq '#VER' ) {
      $Verpost= New-Object -TypeName 'Witsie' 
      $Verpost|Add-Member FileinfoGuid $fileguid
      $Verpost|Add-Member Ver_Serie $konto.D1
      $Verpost|Add-Member Ver_nr $konto.D2
      $Verpost|Add-Member Ver_date $konto.D3
      $Verpost|Add-Member Ver_text $konto.d4
      $Verpost|Add-Member Ver_regdate $konto.d5
      $Verpost|Add-Member Ver_sign $konto.D6
      $stat=Update-WITsqlrecord -Recordset $Ver_table -IDguidfieldname 'Guid' -Object $Verpost -newpost
      $ver_guid=$stat.Guid
      $Ver_row=$konto.row
      $ver_date=$konto.D3
      } else {
      
      $newpost= New-Object -TypeName 'Witsie' 
      $newpost|Add-Member FileinfoGuid $fileguid
      $d4=$konto.d4
      if ($d4.Length -ge 4) {
      $transdatecheck=$konto.d4.substring(0,4)
      } else {
      $transdatecheck="No"
      }
      if ($transdatecheck -eq $ib0startdate.Substring(0,4) ) {
       $siedate=$konto.d4
       $transdate=$true
      } else {
      $siedate=$ver_date
      $transdate=$false
      }
     
      $newpost|Add-Member Account_id $konto.d1
      $newpost|Add-Member Date $siedate
      $newpost|Add-Member Month $siedate.Substring(0,6)
      $newpost|Add-Member Type $konto.Command
      $newpost|Add-Member amount $konto.d3
      $newpost|Add-Member quantity $konto.d6
      $newpost|Add-Member yearno '0'
      $stat=Update-WITsqlrecord -Recordset $Accountstable -IDguidfieldname 'Guid' -Object $newpost -newpost
      $Entry_guid=$stat.Guid
      
      $Entriespost= New-Object -TypeName 'Witsie' 
      $Entriespost|Add-Member AccountentriesGuid $Entry_guid
      $Entriespost|Add-Member Ver_guid $Ver_guid
      $Entriespost|Add-Member FileinfoGuid $fileguid
      $Entriespost|Add-Member Trans_text $konto.D5
      $Entriespost|Add-Member Trans_Object $konto.d2
      $Entriespost|Add-Member Ver_Sign $konto.d7
      $Entriespost|Add-Member Ver_regdate $siedate
      $stat=Update-WITsqlrecord -Recordset $Ver_entries_table -IDguidfieldname 'AccountentriesGuid' -Object $Entriespost -newpost
      
      }
    
      }
    
    $Ver_table.update()
    $Ver_table.updatebatch()
    $Ver_entries_table.update()
    $Ver_entries_table.updatebatch()
    
    $Accountstable.Update()
    $Accountstable.UpdateBatch()
    $Accountstable.close()
    $Ver_table.close()
    $Ver_entries_table.close()
    
    $Tokenset.MoveNext()
    } #Slut While eof
    
    # } ####
}
#endregion Source: Sieimport.ps1

#region Source: sielockperiod.ps1
function Invoke-sielockperiod_ps1
{
    $token='14e4f26d-6bf6-41ed-a4ef-a6c2c54d1274'
    new-WITsiecustomer -integration_user_code 
    get-WITsieToken -Integration_user_API_code '8f0af499-af45-ba99-c887-880280810b37'
    function get-WITsieLoc
    {
        [CmdletBinding()]
        param (
            [Parameter(Position = 0, Mandatory = $true)]
            $Token
        )
        begin
        {
            try
            {
            }
            catch
            {
            }
        }
        process
        {
            try
            {
                $ClientSecret = 'wa5zIksMZ6'
                $Params = @{
                    "Uri"    = 'https://api.fortnox.se/3/settings/lockedperiod'
                    "Method" = 'GET'
                    "Header" = @{
                        "Access-Token"  = $token
                        "Client-Secret" = $ClientSecret
                        "Content-Type"  = "application/json"
                        "Accept"        = "application/json"
                    }
                    "Body"   = @{ }
                    
                }
                
                
                $b = Invoke-WebRequest @Params
                $text = convertfrom-json ($b.Content)
                $text
                
            }
            catch
            {
            }
        }
        end
        {
            try
            {
            }
            catch
            {
            }
        }
    }
    
    get-WITsieLockperiod -token $token
}
#endregion Source: sielockperiod.ps1