powershell - 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 语句。有人可以向我解释我做错了什么,这样我就可以纠正它并希望今天能学到一些东西?:)
解决方案
当脚本复制文件并执行 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
推荐阅读
- python - 数据框只有一列
- html - CSS 在同一个样式表中通过标签样式覆盖 id 样式
- python - 在 jupyter 笔记本上连接 ibm db2 时出错
- html - 为什么我的布局中没有一行中的三个 div?
- typescript - 如何扩充 JS 模块以添加新界面?
- python - 过滤二维 numpy 数组的最快方法
- javascript - 如何避免PHP中的双重登录?
- arrays - 如何将命令的输出添加到 bash 脚本中的数组中?
- python - Django模型将orderlineitems链接在一起,我认为我的视图逻辑可能是问题
- list - 在 Ansible 中滚动带有子列表的列表