how do i edit path from variable?

Shimi 1 Reputation point
2023-02-09T09:25:28.2033333+00:00

I have in multiple locations text files named pc01; pc02; pc03 and so on up to pc18.

I want to go through them in order and get the contant into a single file.

here's the script I use for example:

$source = "C:\Users\Admin\Downloads\80\pc"
$dest = "C:\Users\Admin\Downloads\80\all.txt"
$0 = 0
$1 = 1..9 | ForEach-Object { (Get-Content -Path $source$0$_.txt ) }
$10 = 10..18 | ForEach-Object { (Get-Content -Path $source$_.txt ) }
$1, $10 | Out-File -FilePath $dest

I'm looking to learn how to get it shorter in 2 ways:

  1. how do i add to path from variable without using another variable? there's must be a way to do it in the same line.
  2. when I do 01..18 it translates it to 1 insted of 01 like I intended. is there a way to keep it 2 digits?

and if you have another suggestion how - I'd like to learn!

thanks!

PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,592 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. MotoX80 34,421 Reputation points
    2023-02-09T14:23:06.7+00:00

    Here's one way.

    $source = "C:\Users\Admin\Downloads\80\pc"
    $dest = "C:\Users\Admin\Downloads\80\all.txt"
    $data = 1..18 | ForEach-Object {
        $filename = "{0}{1:D2}.txt" -f $source, $_ 
        write-host $filename                          # display the filename that we built to console  
        Get-Content $filename                         # read content and put in to $data variable  
    }
    "We collected {0} characters." -f $data.Length
    $data | Out-File -FilePath $dest
    
    

    https://devblogs.microsoft.com/scripting/use-powershell-and-conditional-formatting-to-format-numbers/

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.