Skip to content

Commit

Permalink
(UUF) Address feedback on about_* topics (#11173)
Browse files Browse the repository at this point in the history
* (AB#262055) Fix example in about_Function_Provider

This change:

- Addresses an invalid example in the `about_Function_Provider` topic,
  removing an extraneous colon (`:`).
- Fixes AB#262055

* (AB#262067) Add example of invoking function to about_Functions

This change:

- Adds a short example of invoking a newly-defined function to the
  `about_Functions` topic.
- Fixes AB#262067

* (AB#262073) Add functional example to about_For

Prior to this change, the `about_For` topic included
syntactic examples to show and discuss how to create
and use `for` loops, but no practical examples.

This change:

- Renames the existing section from `Examples` to
  `Syntax examples` to accurately describe its content.
- Adds a new `Functional example` section with a longer
  practical example that shows using `for` loops to find,
  rename, and compare files in a folder.
- Fixes AB#262073
  • Loading branch information
michaeltlombardi committed Jun 10, 2024
1 parent 6a495ee commit 9672a80
Show file tree
Hide file tree
Showing 12 changed files with 783 additions and 27 deletions.
180 changes: 178 additions & 2 deletions reference/5.1/Microsoft.PowerShell.Core/About/about_For.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
description: Describes a language command you can use to run statements based on a conditional test.
Locale: en-US
ms.date: 07/21/2021
ms.date: 06/10/2024
online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_for?view=powershell-5.1&WT.mc_id=ps-gethelp
schema: 2.0.0
title: about For
Expand Down Expand Up @@ -119,7 +119,7 @@ for (($i = 0), ($j = 0); $i -lt 10 -and $j -lt 10; $i++,$j++)

For more information, see [about_Logical_Operators](about_Logical_Operators.md).

### Examples
### Syntax examples

At a minimum, a `For` statement requires the parenthesis surrounding the
**Init**, **Condition**, and **Repeat** part of the statement and a command
Expand Down Expand Up @@ -227,6 +227,182 @@ The `For` loop can also be written on one line as in the following example.
for ($i = 0; $i -lt 10; $i++) { Write-Host $i }
```

### Functional example

The following example demonstrates how you can use a `For` loop to iterate over
an array of files and rename them. The files in the `work_items` folder have
their work item ID as the filename. The loop iterates through the files
to ensure that the ID number is zero-padded to five digits.

First, the code retrieves the list of work item data files. They're all JSON
files that use the format `<work-item-type>-<work-item-number>` for their name.
With the file info objects saved to the `$fileList` variable, you can sort them
by name and see that while items are grouped by type, the ordering of the items
by ID is unexpected.

```powershell
$fileList = Get-ChildItem -Path ./work_items
$fileList | Sort-Object -Descending -Property Name
```

```Output
bug-219.json
bug-41.json
bug-500.json
bug-697.json
bug-819.json
bug-840.json
feat-176.json
feat-367.json
feat-373.json
feat-434.json
feat-676.json
feat-690.json
feat-880.json
feat-944.json
maint-103.json
maint-367.json
maint-454.json
maint-49.json
maint-562.json
maint-579.json
```

To ensure that you can sort the work items alphanumerically, the work item
numbers need to be zero-padded.

The code does this by first searching for the work item with the longest
numerical suffix. It loops over the files using a `for` loop, using the index
to access each file in the array. It compares each filename to a regular
expression pattern to extract the work item number as a string instead of an
integer. Then it compares the lengths of the work item numbers to find the
longest number.

```powershell
# Default the longest numeral count to 1, since it can't be smaller.
$longestNumeralCount = 1
# Regular expression to find the numerals in the filename - use a template
# to simplify updating the pattern as needed.
$patternTemplate = '-(?<WorkItemNumber>{{{0},{1}}})\.json'
$pattern = $patternTemplate -f $longestNumeralCount
# Iterate, checking the length of the work item number as a string.
for (
$i = 0 # Start at zero for first array item.
$i -lt $fileList.Count # Stop on the last item in the array.
$i++ # Increment by one to step through the array.
) {
if ($fileList[$i].Name -match $pattern) {
$numeralCount = $Matches.WorkItemNumber.Length
if ($numeralCount -gt $longestNumeralCount) {
# Count is higher, check against it for remaining items.
$longestNumeralCount = $numeralCount
# Update the pattern to speed up the search, ignoring items
# with a smaller numeral count using pattern matching.
$pattern = $patternTemplate -f $longestNumeralCount
}
}
}
```

Now that you know the maximum numeral count for the work items, you can loop
over the files to rename them as needed. The next snippet of code iterates over
the file list again, padding them as needed. It uses another regular expression
pattern to only process files with a numeral count smaller than the maximum.

```powershell
# Regular expression to find the numerals in the filename, but only if the
# numeral count is smaller than the longest numeral count.
$pattern = $patternTemplate -f 1, ($longestNumeralCount - 1)
for (
$i = 0 # Start at zero for first array item.
$i -lt $fileList.Count # Stop on the last item in the array.
$i++ # Increment by one to step through the array.
) {
# Get the file from the array to process
$file = $fileList[$i]
# If the file doesn't need to be renamed, continue to the next file
if ($file.Name -notmatch $pattern) {
continue
}
# Get the work item number from the regular expression, create the
# padded string from it, and define the new filename by replacing
# the original number string with the padded number string.
$workItemNumber = $Matches.WorkItemNumber
$paddedNumber = "{0:d$longestNumeralCount}" -f $workItemNumber
$paddedName = $file.Name -replace $workItemNumber, $paddedNumber
# Rename the file with the padded work item number.
$file | Rename-Item -NewName $paddedName
}
```

Now that the files are renamed, you can retrieve the list of files again and
sort both the old and new files by name. The following snippet retrieves a
the files again to save in a new array and compare with the initial set of
objects. Then it sorts both arrays of files, saving the sorted arrays into
the new variables `$sortedOriginal` and `$sortedPadded`. Finally, it uses a
`for` loop to iterate over the arrays and output an object with the following
properties:

- **Index** represents the current index in the sorted arrays.
- **Original** is the item in the sorted array of original filenamess at the
current index.
- **Padded** is the item in the sorted array of padded filenames at the current
index.

```powershell
$paddedList = Get-ChildItem -path ./work_items
# Sort both file lists by name.
$sortedOriginal = $fileList | Sort-Object -Property Name
$sortedPadded = $renamedList | Sort-Object -Property Name
# Iterate over the arrays and output an object to simplify comparing how
# the arrays were sorted before and after padding the work item numbers.
for (
$i = 0
$i -lt $fileList.Count
$i++
) {
[pscustomobject] @{
Index = $i
Original = $sortedOriginal[$i].Name
Padded = $sortedPadded[$i].Name
}
}
```

```Output
Index Original Padded
----- -------- ------
0 bug-219.json bug-00041.json
1 bug-41.json bug-00219.json
2 bug-500.json bug-00500.json
3 bug-697.json bug-00697.json
4 bug-819.json bug-00819.json
5 bug-840.json bug-00840.json
6 feat-176.json feat-00176.json
7 feat-367.json feat-00367.json
8 feat-373.json feat-00373.json
9 feat-434.json feat-00434.json
10 feat-676.json feat-00676.json
11 feat-690.json feat-00690.json
12 feat-880.json feat-00880.json
13 feat-944.json feat-00944.json
14 maint-103.json maint-00049.json
15 maint-367.json maint-00103.json
16 maint-454.json maint-00367.json
17 maint-49.json maint-00454.json
18 maint-562.json maint-00562.json
19 maint-579.json maint-00579.json
```

In the output, the sorted work items after padding are in the expected order.

## See also

- [about_Comparison_Operators](about_Comparison_Operators.md)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
description: Function
Locale: en-US
ms.date: 01/17/2023
ms.date: 06/10/2024
online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_function_provider?view=powershell-5.1&WT.mc_id=ps-gethelp
schema: 2.0.0
title: about Function Provider
Expand Down Expand Up @@ -162,10 +162,10 @@ in the `Function:` drive, you can omit the drive name.

## Deleting a function

This command deletes the `more:` function from the current session.
This command deletes the `more` function from the current session.

```powershell
Remove-Item Function:more:
Remove-Item Function:more
```

## Changing a function
Expand Down
15 changes: 14 additions & 1 deletion reference/5.1/Microsoft.PowerShell.Core/About/about_Functions.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
description: Describes how to create and use functions in PowerShell.
Locale: en-US
ms.date: 05/17/2024
ms.date: 06/10/2024
online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_functions?view=powershell-5.1&WT.mc_id=ps-gethelp
schema: 2.0.0
title: about Functions
Expand All @@ -25,6 +25,19 @@ Functions can be as simple as:
function Get-PowerShellProcess { Get-Process PowerShell }
```

Once a function is defined, you can use it like the built-in cmdlets. For
example, to call the newly defined `Get-PowerShellProcess` function:

```powershell
Get-PowerShellProcess
```

```Output
NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName
------ ----- ----- ------ -- -- -----------
110 78.72 172.39 10.62 10936 1 powershell
```

A function can also be as complex as a cmdlet or an application.

Like cmdlets, functions can have parameters. The parameters can be named,
Expand Down
Loading

0 comments on commit 9672a80

Please sign in to comment.