I have a script that duplicates a Word doc template and renames each using a csv file with a list of names. What would be the equivalent code if instead of a csv file I use a text file?

Import-csv ‘.\individuals2.csv’ | foreach-object {
	$newname = ‘2 ‘ + $_.name + '.docx’
	Copy-item '.\template.docx' $newname
}
    • mikyopii@programming.dev
      link
      fedilink
      arrow-up
      3
      ·
      edit-2
      7 months ago

      His example doesn’t seem to perform any comparisons to determine what to name the file. If the text file is just a list then something like this could work:

      $file = Get-Content -Path .\individuals2.txt

      foreach ($line in $file) { Copy-Item -Path .\template.docx -Destination “.$(2 + $line + ‘.docs’)” }

      Edit: Wow, Lemmy destroys formatting.

      • brisk@aussie.zone
        link
        fedilink
        arrow-up
        4
        ·
        7 months ago

        It’s markdown, you should be able to indent your lines by 4 spaces or fence with triple backtics to get code blocks. Your client’s editor may have a button to help

        ```
        $file = Get-Content -Path .\individuals2.txt
        
        foreach ($line in $file)
        {
            Copy-Item -Path .\template.docx -Destination ".\$(2 + $line + '.docs')"
        }
        ```
        

        Becomes

        $file = Get-Content -Path .\individuals2.txt
        
        foreach ($line in $file)
        {
            Copy-Item -Path .\template.docx -Destination ".\$(2 + $line + '.docs')"
        }
        
      • BobTheDestroyer@lemy.lolOP
        link
        fedilink
        arrow-up
        1
        ·
        7 months ago

        Thanks for your help, but I had a couple errors pop up when I tried this out. I don’t need to input anything in the code you provided, do I?

        Cannot convert value "VALUE" to type "System.Int32". Error: "Input string was not in a correct format."
        At line:4 char:55
        + ... py-Item -Path .\template.docx -Destination ".\$(2 + $line + '.docs')"
        +                                                     ~~~~~~~~~~~~~~~~~~~
            + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
            + FullyQualifiedErrorId : InvalidCastFromStringToInteger
        
        Copy-Item : Cannot overwrite the item FILENAME with itself.
        At line:4 char:5
        +     Copy-Item -Path .\template.docx -Destination ".\$(2 + $line + '.d ...
        +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            + CategoryInfo          : WriteError: (FILENAME) [Copy-Item], IOException
            + FullyQualifiedErrorId : CopyError,Microsoft.PowerShell.Commands.CopyItemCommand