1

I'm using powershell to run a command like so:

$getlist=rclone sha1sum remote:"\My Pictures\2009\03" --dry-run 
Write-Output $getlist

that outputs a object with the results. Problem being I only want the first column of those results. I've tried things like custom-format --Depth 1 and the other *-format commands but they don't work on this object??

enter image description here

Tony
  • 8,681
  • 7
  • 36
  • 55

2 Answers2

1

that outputs a object with the results

While that is technically true, it is more specifically an [object[]]-typed array of lines ([string] instances) that assigning the stream of output lines - produced by the external rclone program - to a PowerShell variable implicitly created. (Arrays created by PowerShell are [object[]]-typed, even if all the elements are of the same type, such as [string] in this case).

PowerShell fundamentally only "speaks text" when communicating with external programs.

Therefore, to extract substrings from these lines you must perform text parsing, as implied by AdminOfThings' comment on the question.

A simplified approach is to use the unary form of the -split operator:

# Simulate lines input whose first whitespace-separated token is to 
# be extracted.
$getlist = 'foo bar baz', 'more stuff here'

$getlist.ForEach({ (-split $_)[0] })

The above yields:

foo
more

zett42's helpful answer shows a simpler alternative that relies on the -replace operator's (among others) ability to operate directly on each element of an array-valued LHS.

However, the -split approach is useful if you want to extract multiple column values.


If you don't need / want to capture all of the external program's (rclone's) output in memory first, you can use streaming processing in the pipeline, via the ForEach-Object cmdlet:

'foo bar baz', 'more stuff here' | ForEach-Object { (-split $_)[0] }

Note: While slightly slower than collecting all lines in memory up front, the advantage of a pipeline-based approach is reduced memory load: only the extracted substrings are kept in memory (if assigned to a variable).

mklement0
  • 382,024
  • 64
  • 607
  • 775
1

You can use a regular expression to remove the undesired parts of the output:

$getlist = $getlist -replace '\s.*'

When a PowerShell operator such as -replace is applied to a collection, it will be applied to each element individually, creating a new array that stores the results (see Substitution in a collection).

The regular expression removes everything from the first whitespace up to the end of the string.

RegEx breakdown:

  • \s - a single whitespace character like space and tab
  • .* - any character, zero or more times
zett42
  • 25,437
  • 3
  • 35
  • 72