如果我想输出文件hello.txt
,我该怎么做:
-1
hello-1.txt
是否不存在hello-{integer}.txt
答案 0 :(得分:2)
另一种可能性:
if ( test-path hello.txt )
{
$i=0
do { $i++ }
until ( -not ( test-path "hello-$i.txt" ) )
$filename = "hello-$i.txt"
}
else { $filename = 'hello.txt' }
$filename
答案 1 :(得分:1)
此代码应满足您的所有要求。有关详细信息,请参阅内嵌注释。如果需要任何修改,请告诉我。
# 1. Check for existence of hello.txt
$FilePath = "$PSScriptRoot\hello.txt";
if (Test-Path -Path $FilePath) {
# 2. Rename the file to "hello-1.txt" if it exists
Move-Item -Path $FilePath -Destination $FilePath.Replace('hello.txt', 'hello-1.txt');
}
# 3. Test that hello-1.txt doesn't exist
$FilePath2 = "$PSScriptRoot\hello-1.txt";
Test-Path -Path $FilePath2;
# 4. Loop until hello-*.txt doesn't exist
while (Get-ChildItem -Path $PSScriptRoot\hello-[0-9].txt) {
# Loop
Start-Sleep -Seconds 5;
Write-Host -Object 'Looping ...';
}