Powershell Test-Path 和 If 语句,同时执行 if 和 else 语句

时间:2021-06-08 09:24:09

标签: powershell if-statement powershell-ise copy-item

我正在做一些小作业,但我们的老师在解释东西方面做得很糟糕,所以我基本上只是在谷歌上看视频等。

但我必须制作一个脚本,将文件从一个路径复制到另一个路径,如果该文件不存在,它必须给出一个错误。我写了这段代码:

$testpath = Test-Path $destinationfolder
$startfolder = "C:\Desktop\Destination1\test.txt\"
$destinationfolder = "C:\Desktop\Destination2\"

If ($testpath -eq $true) {Copy-Item $startfolder -Destination $destinationfolder}
Else {Write-Host "Error file does not exist!"}

我的问题是,当它成功复制文件时,它仍然打印出错误。它几乎就像完全忽略了 if 和 else 语句。有人可以向我解释我做错了什么,以便我可以纠正它并希望今天能学到一些东西吗? :)

1 个答案:

答案 0 :(得分:1)

当脚本复制文件并执行其他代码块时,我无法复制这个想法。但是:

$testpath = Test-Path $destinationfolder 
$startfolder = "C:\Desktop\Destination1\test.txt\"
$destinationfolder = "C:\Desktop\Destination2\"

您在定义路径(第 3 行)之前检查路径(第 1 行)。 这就是为什么(在新的 shell 会话中执行时)它总是假的。无需在路径末尾放置“\”字符。

你可以这样写:

#Setting variables
$destinationFolder = "C:\Desktop\Destination2"
$startfolder = "C:\Desktop\Destination1\test.txt"

#Checking if destination folder exists
if (Test-Path $destinationFolder) {
    Copy-Item $startfolder -Destination $destinationFolder 
}
else {
    Write-Host "Directory $destinationFolder does not exist!"
}

或者,如果您希望脚本是幂等的(每次都以完全相同的方式运行),它可以如下所示:

$destinationFolder = "C:\Desktop\Destination2"
$file = "C:\Desktop\Destination1\test.txt"

If (!(Test-Path $destinationFolder)) {
    #Check if destinationFolder  is NOT present and if it's not - create it
    Write-Host "Directory $destinationFolder does not exist!"
    New-Item $destinationFolder -ItemType Directory
}

#Will always copy, because destination folder is present
Copy-Item $file -Destination $destinationFolder