Output a range of variables with foreach-object

From DWAMconsult Wiki
Jump to navigation Jump to search
  • Following example creates a range of values 1 - 254 then pipes them to a foreach-object command (using the alias %) that creates an IP address with the final part of the address using each of the values, i.e. an entire class C subnet
$nodes = 1..254 |
  % { "192.168.1.$_" }
  $nodes
  • To output a range of characters you need to prefix with [char[]] to indicate that the output will be multiple characters (hence the nested [] for multiple) and also put [char] before the start and the end values e.g.
[char[]]([char]'a'..[char]'z')
  • E.g. to create folders gbedxwebws44a - h
$range = [char[]]([char]'a'..[char]'h')
foreach ( $char in $range )
{ write-host gbedxwebws44$char }
  • In the following example, there are sixteen files in the current directory named 1 - 16.pdf and this moves them all into a folder: first by enumerating values 1..16, then appending .pdf to each, and saving this into a variable; then finally moves each value in the variable (i.e. each PDF) into the folder called pdf-folder
$pdfs = 1..16 | foreach { "$_.pdf" } ; foreach ( $pdf in $pdfs ) { mv $pdf pdf-folder }