powershell - 连接文件 URL 并检查路径 Powershell 错误
问题描述
我正在尝试从用户那里获取文件路径并连接文件名并在文件夹中创建该文件,然后检查该文件是否存在。文件已创建并且路径对我来说看起来是正确的但是当我尝试使用测试路径检查文件路径是否存在时,它一直失败,它不存在
我可以看到该文件,它存在于我的系统中。当我复制路径并尝试在 Windows 资源管理器中打开时,它给了我一个错误,但是当我尝试右键单击文件并复制名称然后签入 Windows 资源管理器时,它可以工作。我不确定连接是否会添加一些特殊字符。
$fileName = Read-Host -Prompt 'Enter file Name :' #user entered Test123
$filePath = Read-Host -Prompt 'Enter Path:' #user entered C:\Documents
$File = ($filePath + "\" + $fileName + ".json")
If (!(test-path $File)) {
Write-Host "File does not exist"
Exit
}
我究竟做错了什么?我正在尝试从用户获取路径并连接文件名并在文件夹中创建该文件,然后检查该文件是否存在
解决方案
您的串联无效。
根据我们下面的交流,删除了原始响应,因为您已经阐明了您的用例。
Clear-Host
$filePath = Read-Host -Prompt 'Enter Path'
$fileName = Read-Host -Prompt 'Enter file Name'
# Debug - check variable content
($File = "$filePath\$fileName.json")
If (!(test-path $File))
{Write-Warning -Message 'File does not exist'}
# Results - Using a bad name
<#
Enter Path: D:\Temp
Enter file Name: NoFile
WARNING: File does not exist
#>
# Results - using a good file
<#
D:\temp\NewJsonFile.json
#>
或者
Clear-Host
$filePath = Read-Host -Prompt 'Enter Path'
$fileName = Read-Host -Prompt 'Enter file Name'
Try
{
Get-ChildItem -Path "$filePath\$fileName.json" -ErrorAction Stop
Write-Verbose 'Success' -Verbose
}
Catch
{
Write-Warning -Message "Error using $fileName"
$PSitem.Exception.Message
}
# Results
<#
Enter Path: D:\temp
Enter file Name: BadFileName
WARNING: Error using BadFileName
Cannot find path 'D:\temp\BadFileName.json' because it does not exist.
#>
# Results
<#
Enter Path: D:\temp
Enter file Name: NewJsonFile
Directory: D:\temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 05-Oct-20 13:06 0 NewJsonFile.json
VERBOSE: Success
#>
推荐阅读
- python - 使用 5.0V 而不是 3.3V 与 Raspberry Pi GPIO 'in' 引脚
- javascript - 从文本中删除内联样式
- android - 异常:CursorIndexOutOfBoundsException:请求索引 0,大小为 0
- android - 底部导航不起作用
- python - 熊猫用字符串和整数相加行
- scala - 在scala中动态地对案例类字段进行groupBy
- java - 如何在按钮单击时添加小部件?
- jenkins - 区分 Junit Jenkins 插件中的 xml 文件
- android - ConstraintLayout 中的 RecyclerView 项不占其父项的全宽
- java - 无法设置 JSTL 用户变量而不是 java.lang.String