Foreach循环无法在PowerShell中运行

时间:2020-02-12 00:32:23

标签: powershell loops for-loop scripting

我正在寻找有关Powershell中foreach循环的帮助。因此,目标是根据用户请求的数量在PowerShell中制作新文件,因此,如果用户请求制作4个相同的文件,则应在所请求的文件夹中制作4个文件。我只是似乎无法弄清楚为什么我的foreach循环没有制作多个文件。每次只生成一个文件。我已经附加了部分代码。

$FileName = Read-Host "Enter a file name"
$FilePath = Read-Host "Enter a file path"
$FileNumber = Read-Host "How many files need to be created?"
$num = 1

if ($FileName -gt 0) { 

    foreach($num in 4) {
    New-Item -Path $FilePath -Name $filepath
    #Write-Host $number $FileNumber
    }

}

2 个答案:

答案 0 :(得分:2)

$ FileName是字符串,因此尽管If($ FileName -gt 0)将返回true,但这不是一个好习惯。

在数字4中也没有任何内容。In的右侧应该是对象的集合,该对象尚未在脚本中的任何位置创建。然后有一个错字,其中您为名称和路径参数都指定了$ FileName。无论如何,我认为您正在寻找这样的东西:

$FileName = Read-Host "Enter a file name"
$FilePath = Read-Host "Enter a file path"
$FileNumber = Read-Host "How many files need to be created?"
$num = 1

if ($FileName) { 
$num..$FileNumber |
    ForEach-Object{
        $NewFile = $FileName + "_" + $_
        New-Item -Path $FilePath -Name $NewFile -ItemType File
    }
}

if逻辑将适合您的目的。然后,我向ForEach-Object cmdlet的管道发送一系列数字。注意:这与您使用的ForEach关键字不同。无论如何,将数字(在本例中为$ _)与先前输入的基本文件名连接起来,然后继续创建该项目。

希望有帮助,让我知道...

答案 1 :(得分:1)

详细解释Lee_Dailey所说的内容,我编辑了您的代码。在代码内嵌的注释中查看我的注释。

$FileName = Read-Host "Enter a file name"
$FilePath = Read-Host "Enter a file path"
$FileNumber = Read-Host "How many files need to be created?"
# this next line shouldn't be needed here so I commented it out
# $num = 1

# You don't need "-gt 0".  Just use "if ($FileName)". which basically means:
# "if there is a value for $Filename then execute the block"
if ($FileName) {         
    # "foreach" really isn't the right approach here
    # use a for loop instead.  This one means:
    # start counting at $i (which is 1), if $i is less than or
    # equal to $FileNumber then execute the code block
    # and then increment $i at the end, making $i = 2
    # on the second trip through the loop
    for ($i=1; $i -le $FileNumber; $i++){
        # if you are making multiple files you can't give them all the
        # same name.  So you need to add a number at the end of each file
        # you create.  In this case $i
        $thisFileName = "$FileName" + "$i"
        New-Item -Path $FilePath -Name $thisFileName
        #Write-Host $number $FileNumber
    }

}