我正在做一些小的学校作业,但我们的老师在讲解方面做得很糟糕,所以我基本上只是在谷歌上看视频等。
但我必须编写一个脚本,将一个文件从一个路径复制到另一个路径,如果该文件不存在,它必须给出一个错误。我写了这段代码:
$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语句。谁能给我解释一下我做错了什么,这样我就可以改正它,希望今天能学到点什么?:)
发布于 2021-06-08 17:47:03
当脚本复制文件并执行else代码块时,我无法复制这种想法。但是:
$testpath = Test-Path $destinationfolder
$startfolder = "C:\Desktop\Destination1\test.txt\"
$destinationfolder = "C:\Desktop\Destination2\"在定义路径(第3行)之前,您正在检查路径(第1行)。这就是(当在新的shell会话中执行时)它总是为false的原因。不需要在路径的末尾加上"\“字符。
您可以像这样编写相同的代码:
#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 $destinationFolderhttps://stackoverflow.com/questions/67884915
复制相似问题