powershell - 使用 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
- for($directs 中的$folders){ 表达式或语句中出现意外标记“in”。
- 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."
}
请指导我
解决方案
嗨,欢迎来到!
您的 for 循环的语法有错误。伪代码中 for 循环的基本示例是:
for ($init; $condition; $operator) {
}
在您的示例中,它应该(您的代码没有$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."
}
推荐阅读
- node.js - 节点 JS 会话代码无法在同一页面再次重定向
- python - 找到正确的 api 以在 bing websearch 包中使用
- azure-functions - 扩展运算符在 Azure 节点函数中不可用
- python-3.x - 如果我在 Python 3 环境中安装带有 pip 的包,该包是否保证与 Python 3 兼容?
- java - 如何通过一堂课
成哈希图? - java - 想要开发动态检查父 Web 元素中存在的子 Web 元素的 Java 逻辑
- python - 解决使用 pip install 时出现的无效语法错误
- vba - 我有 2 个循环,结果不好
- javascript - 如何修复 WSO2 EI (v6.4.0) 中的“jsonPath is not defined”错误
- flutter - Flutter:按下按钮时播放声音