首页 > 解决方案 > 连接文件 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 
    }

我究竟做错了什么?我正在尝试从用户获取路径并连接文件名并在文件夹中创建该文件,然后检查该文件是否存在

标签: powershellpowershell-core

解决方案


您的串联无效。

根据我们下面的交流,删除了原始响应,因为您已经阐明了您的用例。

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
#>

推荐阅读