使用PowerShell ISE我想使用For Loop在文件夹中创建文件夹,在每个这样的文件夹中,再次使用For Ea



在下面的代码中,我想要实现"For"one_answers"ForEach",这将在"C: \ for Each循环的示例文件";每个中的目录和示例文本文件

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

  • for($directs中的$folders({表达式或语句中出现意外的标记"in"。
    • 类别信息:ParserError:(:([],ParentContainsErrorRecordException
    • FullyQualifiedErrorId:意外的令牌*

#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 "$sampleSampleFile.txt" -Value "Hello World 1"
Add-Content -Path "$sampleSampleFile1.txt" -Value "Hello World 2"
Write-Host "$sample done."
}

请引导我

嗨,欢迎加入SO!

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

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

}

此处的文档:https://learn.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 "$dirSampleFile.txt" -Value "Hello World 1"
Add-Content -Path "$dirSampleFile1.txt" -Value "Hello World 2"
Write-Host "$dir done."
}

相关内容

最新更新