Home > Mobile >  how to split Strings into Arrays?
how to split Strings into Arrays?

Time:12-29

how can I have $data outside my .Click event to later use in a different .Click event:

Username       : John
Device         : Lenovo T15
Headset        : Hyper Cloud 2
Dockingstation : Wavelink
Monitor        : HP
Transponder    : 002

I want to obtain each line individually, for instance: $array[1] = "John", $array[2] = "Lenovo T15" and so on. I was just able to get something like that: John Device.

Output getting gathered from a csv and displayed on Textbox in an GUI builded script:

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Windows.Forms.Application]::EnableVisualStyles();

 

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()

$csvData = Import-Csv -path 'C:\temp\offboarding_skript.csv' -Header "Username", "Device", "Headset", "Dockingstation", "Monitor", "Transponder" 


function search_csv {
    $searchThis = $textbox_Search.Text.Trim()
    # use $script: scoping here to reference the $csvData variable
    $data = $script:csvData | Where-Object {$_.Username -like "*$searchThis*"}
    if ([string]::IsNullOrWhiteSpace($searchThis)) {
        $output_TextBox.Clear()
    }
    elseif ($data) {
        $output_TextBox.Text =  ($data| Format-List | Out-String).Trim() 
    }

    else {
        $output_TextBox.Text = "Nichts gefunden .."

        }
      }

     
    $search_csvtool = New-Object System.Windows.Forms.Form
    $search_csvtool.Text = "Offboarding-Skript"
    $search_csvtool.Size = New-Object System.Drawing.Size(674,500)
    $search_csvtool.FormBorderStyle ="FixedDialog"
    $search_csvtool.Backcolor="white"
    $search_csvtool.TopMost = $true
    $search_csvtool.MaximizeBox = $false
    $search_csvtool.MinimizeBox = $true
    $search_csvtool.ControlBox = $true
    $search_csvtool.StartPosition = "CenterScreen"
    $search_csvtool.Font = "Microsoft Sans Serif"


    $label_Search = New-Object System.Windows.Forms.Label
    $label_Search.Location = New-Object System.Drawing.Size(195,18)
    $label_Search.Size = New-Object System.Drawing.Size(265,32)
    $label_Search.TextAlign ="MiddleCenter"
    $label_Search.Text = "Bitte Nutzernamen eingeben:"
    $search_csvtool.Controls.Add($label_Search)


    $textbox_Search = New-Object System.Windows.Forms.TextBox
    $textbox_Search.Location = New-Object System.Drawing.Size(195,50)
    $textbox_Search.Size = New-Object System.Drawing.Size(266,37)
    $search_csvtool.Controls.Add($textbox_Search)


    $button_Search = New-Object System.Windows.Forms.Button
    $button_Search.Location = New-Object System.Drawing.Size(195,80)
    $button_Search.Size = New-Object System.Drawing.Size(266,24)
    $button_Search.TextAlign = "MiddleCenter"
    $button_Search.Text = "Suche"
    $button_Search.Add_Click({search_csv})
    $search_csvtool.Controls.Add($button_Search) 


    $output_TextBox = New-Object System.Windows.Forms.TextBox
    $output_TextBox.Multiline = $true;
    $output_TextBox.Location = New-Object System.Drawing.Size(130,130)
    $output_TextBox.Size = New-Object System.Drawing.Size(400,250)
    $output_TextBox.ScrollBars = "Vertical"
    $output_TextBox.ReadOnly = $true;
    $search_csvtool.Controls.Add($output_TextBox)
    $search_csvtool.Add_Shown({$search_csvtool.Activate()})

    
    #Print Button zum drucken der ausgegebenen Textzeile
    $PrintButton = New-Object System.Windows.Forms.Button
    $PrintButton.Location = New-Object System.Drawing.Size(35,420)
    $PrintButton.Size = New-Object System.Drawing.Size(75,23)
    $PrintButton.Text = "Drucken"
    $PrintButton.Name = "Drucken"
    $PrintButton.Add_Click(({#Path
$template = "c:\tempory\Inventarliste.docx"
$tempFolder = $env:TEMP   "\Populate-Word-DOCX"

# unzip function
Add-Type -AssemblyName System.IO.Compression.FileSystem
function Unzip {
    param([string]$zipfile, [string]$outpath)
    [System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath)
}
function Zip {
    param([string]$folderInclude, [string]$outZip)
    [System.IO.Compression.CompressionLevel]$compression = "Optimal"
    $ziparchive = [System.IO.Compression.ZipFile]::Open( $outZip, "Update" )

    # loop all child files
    $realtiveTempFolder = (Resolve-Path $tempFolder -Relative).TrimStart(".\")
    foreach ($file in (Get-ChildItem $folderInclude -Recurse)) {
        # skip directories
        if ($file.GetType().ToString() -ne "System.IO.DirectoryInfo") {
            # relative path
            $relpath = ""
            if ($file.FullName) {
                $relpath = (Resolve-Path $file.FullName -Relative)
            }
            if (!$relpath) {
                $relpath = $file.Name
            } else {
                $relpath = $relpath.Replace($realtiveTempFolder, "")
                $relpath = $relpath.TrimStart(".\").TrimStart("\\")
            }

            # display
            Write-Host $relpath -Fore Green
            Write-Host $file.FullName -Fore Yellow

            # add file
            [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($ziparchive, $file.FullName, $relpath, $compression) | Out-Null
        }
    }
    $ziparchive.Dispose()
}

# prepare folder
Remove-Item $tempFolder -ErrorAction SilentlyContinue -Recurse -Confirm:$false | Out-Null
mkdir $tempFolder | Out-Null

# unzip DOCX
Unzip $template $tempFolder

# replace text
$bodyFile = $tempFolder   "\word\document.xml"
$body = Get-Content $bodyFile
$body = $body.Replace("[placeholder1]", "$Username")
$body = $body.Replace("[placeholder2]", "$Device")
$body = $body.Replace("[placeholder3]", "$Headset")
$body = $body.Replace("[placeholder4]", "$Dockingstation")
$body = $body.Replace("[placeholder5]", "$Monitor")
$body = $body.Replace("[placeholder6]", "$Transponder")
$body | Out-File $bodyFile -Force -Encoding ascii

# zip DOCX
$destfile = $template.Replace(".docx", "-after.docx")
Remove-Item $destfile -Force -ErrorAction SilentlyContinue
Zip $tempFolder $destfile

# clean folder
Remove-Item $tempFolder -ErrorAction SilentlyContinue -Recurse -Confirm:$false | Out-Null}))
    $search_csvtool.Controls.Add($PrintButton) 


    #Abbrechen Button
    $CancelButton = New-Object System.Windows.Forms.Button
    $CancelButton.Location = New-Object System.Drawing.Size(560,420)
    $CancelButton.Size = New-Object System.Drawing.Size(75,23)
    $CancelButton.Text = "Abbrechen"
    $CancelButton.Name = "Abbrechen"
    $CancelButton.DialogResult = "Cancel"
    $CancelButton.Add_Click({$objForm.Close()})
    $search_csvtool.Controls.Add($CancelButton)
    

    
     
  

  

    [void] $search_csvtool.ShowDialog()

Thank you all in advance!

CodePudding user response:

Focusing mainly on the parts of the code where you are in need of help, first your "search" function which for the most part is correct, you just need a way to preserve the $data result outside of the scope of your Click event, for that we can use any reference type, in this case a hash table.

# import Csv here as you're already doing
$csvData = Import-Csv 'C:\temp\offboarding_skript.csv' -Header ....

# we will use this hashtable to store the `$data`
# in the parent scope so we can re-use it in the `$PrintButton` Click Event
$result  = @{}

function search_csv {
    $searchThis = $textbox_Search.Text.Trim()

    if ([string]::IsNullOrWhiteSpace($searchThis)) {
        # exit early
        return $output_TextBox.Clear()
    }

    # no need for `$script:` to read a parent scope variable,
    # not sure where you got that information but is wrong
    $data = $csvData | Where-Object { $_.Username -like "*$searchThis*" }

    if($data) {
        # here we can send `$data` to the parent scope
        $result['Value'] = $data
        $output_TextBox.Text = ($data | Format-List | Out-String).Trim()
        # exit early from this event
        return
    }

    # if above conditions were false, then we can assume
    # no object was found, remove the Value from the outside hashtable
    $result.Remove('Value')
    $output_TextBox.Text = "Nichts gefunden .."
}

Now that we have $data (an actual PSCustomObject) we don't have a need to parse or split or anything else but dot notation to get it's values. Note that, probably here you will need to handle what happens if there is more than 1 result from your search (should this create more than Xml?), its also worth noting you shouldn't be treating an Xml as plain text and doing plain text replacement but that's out of the scope of this question.

# rest of the code is left as-is, focusing in this event
$PrintButton.Add_Click({
    # start of this event can remain as-is...

    # this is the part where you needed help, here we can do this:
    $data = $result['Value']
    # now `$data` is the same object or objects that resulted from
    # the `search_csv` function!

    $bodyFile = $tempFolder   "\word\document.xml"
    $body = Get-Content $bodyFile -Raw

    # since `$data` is an object we can just use dot notation here!
    $body = $body.Replace("[placeholder1]", $data.UserName)
    $body = $body.Replace("[placeholder2]", $data.Device)
    $body = $body.Replace("[placeholder3]", $data.Headset)
    $body = $body.Replace("[placeholder4]", $data.Dockingstation)
    $body = $body.Replace("[placeholder5]", $data.Monitor)
    $body = $body.Replace("[placeholder6]", $data.Transponder)
    $body | Out-File $bodyFile -Force -Encoding ascii

    # rest of this event remain as-is....
})
$search_csvtool.Controls.Add($PrintButton)
  • Related