首页 > 解决方案 > 使用 PowerShell ISE 我想使用 For Loop 在文件夹中创建文件夹,并在每个这样的文件夹中,再次使用 For Each Loop 创建示例 txt 文件

问题描述

在下面的代码中,我想同时实现“For”和“ForEach”,这将在“C:\Sample Files for ForEach Loop”目录中创建文件夹,并在每个文件夹中创建示例文本文件

运行代码后,会弹出一条错误消息: *At C:\Users\Nick\For Each scripting Construct.ps1:14 char:10


#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."
}

请指导我

标签: powershell

解决方案


嗨,欢迎来到!

您的 for 循环的语法有错误。伪代码中 for 循环的基本示例是:

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

此处的文档:https ://docs.microsoft.com/pl-pl/powershell/module/microsoft.powershell.core/about/about_for?view=powershell-5.1

在您的示例中,它应该(您的代码没有$folders启动变量)看起来像:

#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."
}

推荐阅读