Home > Software engineering >  How to enter get-childitem in to a string
How to enter get-childitem in to a string

Time:09-18

I am tring to create a script that will output the name of .txt files via for loop that counts the number of files and creates an option to open .txt file from just one click.

$s = (Get-ChildItem -Path C:\*.txt -Name | Measure-Object -Line).Lines

for($i=0; $1 -gt 5 ;$i  )
{
    $c = [string[]](Get-ChildItem -Path C:\*.txt -Name)
    [void] $objListBox.Items.Add('$i')
    Write-Output $c
}

I am stuck with Get-childitem like in $c to get the list of file names into a variable so i can split or get the line for user option.

Thanks in advance

CodePudding user response:

You can use the Example screenshot of form

$basePath = "C:\"
$SearchString = Join-Path $basePath "*.txt"
$filenames = @(Get-ChildItem -Path $SearchString -Name | Sort)
$count = $filenames.count

#All you need for System.Windows.Forms to work
Add-Type -AssemblyName System.Windows.Forms

# Variables for generating size
$ButtonHeight = 35
$ButtonWidth = 450
$WindowTitle = "Choose a file"
$BottomSpace = $StartHeight = 10
$LeftSpace = $RightSpace = 30
$CurrentHeight = $Startheight
$FormHeight = 60   $BottomSpace   $StartHeight   $ButtonHeight * $count
$FormWidth = 20   $LeftSpace   $RightSpace   $ButtonWidth

# Create the form
$form = New-Object System.Windows.Forms.Form
$form.Text = $WindowTitle
$form.Size = New-Object System.Drawing.Size($FormWidth,$FormHeight)
$form.FormBorderStyle = "Fixed3d" # Sizeable: User may change size - Fixed3d: User may not change size
$form.StartPosition = "CenterScreen"
$Form.AutoScroll = $True # Scrollbars when you need it
$form.Topmost = $true #always on top
$form.MaximizeBox = $false #Allows to maximize window

# Generate the buttons in a foreach and arrange them
foreach ($filename in $filenames) {
    $GeneratedButton = New-Object System.Windows.Forms.Button
    $GeneratedButton.Location = New-Object System.Drawing.Size($LeftSpace,$CurrentHeight)
    $GeneratedButton.Size = New-Object System.Drawing.Size($ButtonWidth,$ButtonHeight)
    $GeneratedButton.Text = $filename
    # Action to take when button is clicked -- Open file and close form
    $GeneratedButton.Add_Click({ Start-Process (Join-Path $BasePath $this.text) ; $form.Close() })
    $form.Controls.Add($GeneratedButton)
    $CurrentHeight  = $ButtonHeight
}

# Activate the Form when loaded
$form.Add_Load({
    $form.Activate()
})
# Show the form when loaded, but hide any results
$form.ShowDialog() > $null  # Trash any output
  • Related