0
votes

In the code Below I want to achieve both 'For' and 'ForEach' which will create folders in "C:\Sample Files for ForEach Loop" directory and sample text files in each

After running the code an error message Pops up stating : *At C:\Users\Nick\For Each scripting Construct.ps1:14 char:10

  • for($folders in $directs){ Unexpected token 'in' in expression or statement.
    • CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
    • FullyQualifiedErrorId : UnexpectedToken*

#Address of folder
$directs = @("C:\Sample Files for ForEach Loop")


# 1. Creating an array of Folders using For Loop 
for($folders in $directs){
    $folders = New-Item -Path "C:\Sample Files for ForEach Loop" -ItemType Directory
}

#2. Using For Each Loop to create sample Textfiles inside them 
foreach($sample in $folders) {
    Add-Content -Path "$sample\SampleFile.txt" -Value "Hello World 1"
    Add-Content -Path "$sample\SampleFile1.txt" -Value "Hello World 2"
    Write-Host "$sample done."
}

Please guide me

1

1 Answers

1
votes

Hi and welcome on SO!

There is an error in a syntax of your for loop. Basic example for for loop in pseudocode is:

for ($init; $condition; $operator) {
    
}

Documentation here: https://docs.microsoft.com/pl-pl/powershell/module/microsoft.powershell.core/about/about_for?view=powershell-5.1

In your example it should (your code does not have $folders variable initiated) look something like:

#Address of folder
$directs = @("C:\Sample Files for ForEach Loop")


##Select one of the 2 approaches
# 1. For loop approach 
for ($i = 0; $i -lt $directs.Length; $i++) {
    $dir = $directs[$i]
    New-Item -Path $dir -ItemType Directory -Verbose | Out-Null
    Add-Content -Path "$dir`\SampleFile.txt" -Value "Hello World 1"
    Add-Content -Path "$dir`\SampleFile1.txt" -Value "Hello World 2"
    Write-Host "$dir done."
}

# 2. ForEach approach
foreach ($dir in $directs) {
    New-Item $dir -Force -ItemType Directory -Verbose
    Add-Content -Path "$dir\SampleFile.txt" -Value "Hello World 1"
    Add-Content -Path "$dir\SampleFile1.txt" -Value "Hello World 2"
    Write-Host "$dir done."
}