连接文件网址并检查路径Powershell错误

问题描述

我试图从用户那里获取文件路径,并连接文件名,然后在文件夹中创建该文件,然后检查该文件是否存在。文件已创建,路径对我来说似乎正确,但是当我尝试使用test-path检查文件路径是否存在时,会不断显示该路径不存在

我可以看到该文件,并且该文件存在于我的系统中。当我复制路径并尝试在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
#>
,

如果该目录不存在,则也需要创建该目录。

$fileName = Read-Host -Prompt 'Enter file Name :'     #user entered Test123
$filePath = Read-Host -Prompt 'Enter Path:'   #user entered C:\Documents

$File = (Join-Path $filePath "$fileName.json")

If (test-path $filePath)
{
    Write-Host Folder exists! -ForegroundColor Cyan
}
else
{
    Write-Host Folder does not exist! -ForegroundColor Yellow
    $result = New-Item $filePath -ItemType Directory

    if($result)
    {
        Write-Host Folder created successfully! -ForegroundColor Green
    }
}

If (test-path $File)
{
    Write-Host File exists! -ForegroundColor Cyan
}
else
{
    Write-Host File does not exist! -ForegroundColor Yellow
    $result = New-Item $file -ItemType File

    if($result)
    {
        Write-Host File created successfully! -ForegroundColor Green
    }
}