在现有文件之上创建新文件

时间:2019-01-09 11:31:38

标签: windows powershell

我对PowerShell脚本非常陌生。 我正在尝试创建一个PowerShell脚本,该脚本将在给定的文件夹(路径)中创建新的自定义文件

假设我已经输入了$pfad$ext(即.txt)。我为$anz输入了数字2。我在文件夹中的输出如下:

“ Created_File 1.txt”和“ Created_File 2.txt”

#Enter Path where the files should be created
$pfad = Read-Host "Pfadeingabe "  

#Enter Number of files that should be generated
$anz = Read-Host "Anzahl an Dateien "

#Enter a file extension
$ext = Read-Host "Dateierweiterung (txt, pdf) "  

#Name of the standard created file
$name = "Created_File" 

#loop through the given number of files that should be created
for($i=1; $i -le $anz; $i++)
{
    #Check if the files already exist
    #if(Test-Path -Path "$pfad\$name $i.$ext" )
    #{
        #Code to create the given number of files with another name
    #}
    New-Item -Path $pfad -Name "$name $i.$ext" -ItemType "file"
}

现在文件已经存在,我想在powershell中检查它是否与for循环中的if语句一起使用。 假设我为$anz输入了数字2。当我的for循环现在循环时,if语句检查是否已经存在2个具有相同名称的文件。

我现在想要的是数字继续。这样我的文件夹中就会有“ Created_File 3.txt”和“ Created_File 4.txt”输出。 如果我再次输入$anz 2,则输出应该像“ Created_File 5.txt”和“ Created_File 6.txt”一样继续

但是我不知道该怎么做。你能帮我吗?

我希望你能理解我的问题和我想要的东西。

1 个答案:

答案 0 :(得分:0)

有多种方法可以解决此类问题,最基本的方法(恕我直言)是搜索与文件$name匹配的现有文件数,然后从那里开始计数:

#Enter Path where the files should be created
$pfad = Read-Host "Pfadeingabe "  

#Enter Number of files that should be generated
$anz = Read-Host "Anzahl an Dateien "

#Enter a file extension
$ext = Read-Host "Dateierweiterung (txt, pdf) "  

#Name of the standard created file
$name = "Created_File" 

$existingFileNumber = get-childitem -Path $pfad -Filter "$name *.txt" | Measure-Object | Select-Object -ExpandProperty Count

#loop through the given number of files that should be created
for($i=$existingFileNumber +1 ; $i -le [int]$anz + $existingFileNumber; $i++)
{
    New-Item -Path $pfad -Name "$name $i.$ext" -ItemType "file"
}
相关问题