0

This script is supposed to create a file or files and if there is more than 1 put 1 after name then 2 then 3 and so on.. and if its 0 or less to say: You must select at least one file to be created

$Filename=Read-Host "Enter desired filename"
$NewFilePath=Read-Host "Enter desired path"
$AmtOfFiles=Read-Host "Enter desired amount of files"

if($AmtOfFiles -ge 1){
for($AmtOfFiles=1;$AmtOfFiles -gt 0){
New-Item -ItemType file -Path $NewFilePath -Name $Filename$i
$i++
}
}
else{Write-Output "You must select at least one file to be created.”}```
1
  • please Read The Friendly Manual - specifically look at Get-Help about_For. the examples make your "endless loop" problem quite clear. [grin] Commented Feb 16, 2020 at 3:56

1 Answer 1

1

You can get help on the for command from PowerShell by typing:

get-help about_for

You can also see this Microsoft site for the same info.

The for command has 3 parameters in the parens, not the two you are using in your example.

for (<init>; <condition>; <repeat>) 
{<statement list>}

You need to use a control variable, like $i, in the definition of the For. So modifying your code, it would look like this:

If($AmtOfFiles -ge 1){
    for($i=1;$i -lt $AmtOfFiles;$i++)
    {
        New-Item -ItemType file -Path $NewFilePath -Name $Filename$i
    }
}
else{
    Write-Output "You must select at least one file to be created.”
}

Please read the documentation for more info on how to use for loops properly. You'll be happy you did.

Hope this helps.

Sign up to request clarification or add additional context in comments.

2 Comments

appreciate it and will do right now, just always forgetting basic stuff that i should know! i get that i was missing the condition
@DavidBrand Have you seen these last two comments?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.