首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Powershell测试-Path和If语句,同时执行if和else语句

Powershell测试-Path和If语句,同时执行if和else语句
EN

Stack Overflow用户
提问于 2021-06-08 17:24:10
回答 1查看 35关注 0票数 0

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

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

代码语言:javascript
复制
$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语句。谁能给我解释一下我做错了什么,这样我就可以改正它,希望今天能学到点什么?:)

EN

回答 1

Stack Overflow用户

发布于 2021-06-08 17:47:03

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

代码语言:javascript
复制
$testpath = Test-Path $destinationfolder 
$startfolder = "C:\Desktop\Destination1\test.txt\"
$destinationfolder = "C:\Desktop\Destination2\"

在定义路径(第3行)之前,您正在检查路径(第1行)。这就是(当在新的shell会话中执行时)它总是为false的原因。不需要在路径的末尾加上"\“字符。

您可以像这样编写相同的代码:

代码语言:javascript
复制
#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!"
}

或者,如果你想让脚本是幂等的(每次都以完全相同的方式运行),它可以看起来像这样:

代码语言:javascript
复制
$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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67884915

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档