I have a basic PowerShell script that prompts for a partial string, searches (recursively) through the current folder and returns a list of files. It then prompts to ask what file the user wants to launch and opens the item when selected.
What's odd is that the output doesn't appear on the screen until after the read-host for item selection.
Here's an example:
$name = read-host "name?" # The search string
# Grab everything that matches the partial string
$searchlist = dir -recurse -filter "*$name*" | select FullName
# Create an empty array
$searchtable = @()
$number = 0
# Assign a number for each file to ease selection
$searchlist | foreach {
$number++
$o = [PSCustomObject]@{
Number = $number
Name = $_.FullName
}
$searchtable += $o
}
# Ensure the returned list is sorted by number
$sorted = $searchtable | sort Number
# Attempting to return the list here doesn't actually do anything
# The list is not displayed until after entering an item to the read-host
$sorted
$selectedvid = read-host "which one?"
$vid = $searchtable | where {$_.number -eq $selectedvid} | select -ExpandProperty Name
invoke-item -literalpath $vid
Working around this is reasonably trivial (the following works):
$name = read-host "name?"
$searchlist = dir -recurse -filter "*$name*" | select FullName
$searchtable = @()
$number = 0
$searchlist | foreach {
$number++
$o = [PSCustomObject]@{
Number = $number
Name = $_.FullName
}
$searchtable += $o
}
$sorted = $searchtable | sort Number
write-host "Number Name"
write-host "------ -----------------"
$sorted | foreach {write-host $($_.Number.ToString().PadRight(6,' ')) $_.Name}
$selectedvid = read-host "which one?"
$vid = $searchtable | where {$_.number -eq $selectedvid} | select -ExpandProperty Name
invoke-item -literalpath $vid
I just cannot figure out why the output isn't dumped to screen prior to entering a value into the $selectedVid variable.
Running PowerShell 5.1 on Windows 11.