所以我有一个任务,我必须创建一个 PowerShell 脚本,它需要三个参数,“$foldername”、“$filename”和“$number”。
该脚本检查文件夹“$foldername”是否存在,如果不存在,则创建它。之后,它会创建与“$number”指定一样多的名为“$filename”的新文件。之后,它会报告已创建的文件数量并列出它们。
到目前为止我所拥有的。
Param (
[string]$foldername,
[string]$filename,
$number=1
)
if ((Test-Path -Path $foldername) -ne $true) {
new-item -path $foldername -ItemType directory #if the folder doesn't exist, create it.
}
$new_file= $foldername+"\$_"+$filename #save the path and name of the new file to an variable
if ((Test-Path -Path $new_file* -PathType leaf) -eq $true) {
Write-Host "$filename already exists in $foldername"
break #if a file with a name that contains $filename in it exists in $foldername, break and do not create any new files.
}
$null=1..$number | foreach { new-item -path $foldername -name $_$filename } #create new files using foreach.
write-host ("Created $number new files") #tell the user how many files were created
Get-ChildItem -path $foldername | where-object Name -like *$filename* | format-table Name #show the created files in a table format, formatted by name
这个脚本有一些问题和磨损的解决方案,但主要问题是新文件的创建。由于新文件的名称来自 $filename,因此只需像这样运行脚本:
./script.ps1 -foldername C:\users\example\testing -filename "test.txt" -number 5
不起作用,因为它尝试创建 5 个名为“test.txt”的文件并且只会返回错误。
我通过使用“foreach”并命名文件 $_$filename 来解决它
1test.txt
2test.txt
...
5test.txt
但我发现正确的方法是:
test1.txt
test2.txt
...
test5.txt
该数字应该以某种方式在文件名中运行,但我不知道该怎么做。
如果您弄清楚如何检查 $filename 文件是否已存在于目标文件夹中,则会获得奖励积分。