如何编写接受相对路径的Powershell文件参数

如何编写接受相对路径的Powershell文件参数,powershell,parameters,Powershell,Parameters,当PSD1的路径为完全限定路径(或当前位置与当前目录相同)时,以下示例代码正确读取PSD1和常规文件。 当提供相对路径时,它将失败 param ( [Parameter(Mandatory=$true)][System.IO.FileInfo]$PsdFile, [Parameter(Mandatory=$false)][System.IO.FileInfo]$RegularFile = 'testfile' ) $RegularFileContent = Get-Conten

当PSD1的路径为完全限定路径(或当前位置与当前目录相同)时,以下示例代码正确读取PSD1和常规文件。 当提供相对路径时,它将失败

param (
    [Parameter(Mandatory=$true)][System.IO.FileInfo]$PsdFile,
    [Parameter(Mandatory=$false)][System.IO.FileInfo]$RegularFile = 'testfile'
)

$RegularFileContent = Get-Content $RegularFile
$PsdData = Import-LocalizedData -BaseDirectory $PsdFile.DirectoryName -FileName $PsdFile.Name

echo "regular file contents: $RegularFileContent"

echo "Psd data:"
echo $PsdData.Name
如何修复此问题,以便用户可以输入相对路径


我相信潜在的问题与中描述的问题类似,但我不知道如何将
解析路径
或类似内容纳入参数处理。

您的许多问题取决于您所指的相对,因为它本身就是相对的。如果希望路径相对于用户的工作目录而不是脚本的根目录,可以这样完成:

param(
    [Parameter(Mandatory)]
    [string]
    $PsdFile,

    [Parameter()] # Mandatory is $false by default
    [string]
    $RegularFile = 'testfile'
)

[System.IO.FileInfo]$psd = Join-Path -Path $PWD.Path -ChildPath $PsdFile

$data = Import-LocalizedData -BaseDirectory $psd.DirectoryName -FileName $PsdFile.Name
$content = Get-Content -Path $RegularFile

"regular file contents: $content"
"Psd data:" + $data.Name

相对于什么?脚本根?用户会话?如果
$PsdFile
不是完全限定的路径,则此操作将失败。因此,任何相对路径都会导致此问题。谢谢。我不得不让这一点下沉,我昨天已经看了太久,无法理解你关于为什么会有不同的评论。我仍然觉得无论输入哪一个,问题都会出现,但解决方案显然会有所不同。这个解决方案有效。我只想测试当您指定的路径不是有效(相对)路径时会发生什么。
param (
    [Parameter(Mandatory = $true)]
    [ValidateScript( {
            if (-Not (Test-Path -Path $_ ) ) { throw "File not found." }
            elseif (-Not (Test-Path -Path $_ -PathType Leaf) ) { throw "PsdFile should be a file." }
            return $true
        })]
    [System.IO.FileInfo] $PsdFile,

    [Parameter(Mandatory = $false)]
    [ValidateScript( {
            if (-Not (Test-Path -Path $_ ) ) { throw "File not found." }
            elseif (-Not (Test-Path -Path $_ -PathType Leaf) ) { throw "PsdFile should be a file." }
            return $true
        })]
    [System.IO.FileInfo] $RegularFile = 'testfile'
)

$PsdFile = (Resolve-Path -Path $PsdFile).Path;
$RegularFile = (Resolve-Path -Path $RegularFile).Path;

$RegularFileContent = Get-Content $RegularFile.FullName
$PsdData = Import-LocalizedData -BaseDirectory $PsdFile.DirectoryName -FileName $PsdFile.Name