首页 > 解决方案 > Powershell Test-Path and If 语句,同时执行 if 和 else 语句

问题描述

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

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

$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 语句。有人可以向我解释我做错了什么,这样我就可以纠正它并希望今天能学到一些东西?:)

标签: powershellif-statementpowershell-isecopy-item

解决方案


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

$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

推荐阅读