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

解决方法

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

$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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...