【发布时间】:2021-02-06 03:09:36
【问题描述】:
在 Python 中,有一个简单的衬线可以采用类似 C:\somefolder\somesubfolder\file.csv 的路径,如果存在 C:\somefolder\somesubfolder\ 部分,则获取它,并告诉您它是否有效。我必须考虑到用户可能会传入绝对路径、相对路径或根本没有路径,并且文件只是写入同一目录。一些潜在的用户输入:
..\an_invalid_folder\something.csvC:\an invalid folder\something.csvsomething.csvsome_absolute_path\something.csv
在 PowerShell 中,我发现这非常麻烦。我发现像 Split-Path 这样的东西有奇怪的行为 - 例如:如果你只传递 C:\ 然后使用叶子选项运行分割路径,它会告诉你 C:\ 是叶子。现在,我明白他们为什么这样做了,但这使得解决上述问题有点难看。下面是我想出的 - PowerShell 没有像 os.path 库这样更干净地处理所有这些情况的东西吗?
$ParentPath = $(Split-Path -Path $OutputFilePath -Parent)
if ($ParentPath -ne "") {
if (-not $(Test-Path -PathType Container $ParentPath)) {
Write-Error "The path you provided for $($OutputFilePath) is not valid." -ErrorAction Stop
}
}
if (Test-Path $(Split-Path -Path $OutputFilePath -Leaf) -PathType Container) {
Write-Error "You must provide a filename as part of the path. It looks like you only provided a folder in $($OutputFilePath)!" -ErrorAction Stop
}
Try { [io.file]::OpenWrite($outfile).close() }
Catch { Write-Error "It looks like you may not have permissions to $($OutputFilePath). We tried to open a file object there and the test failed." -ErrorAction Stop }
【问题讨论】:
-
想要单线?
(@(Split-Path $OutputFilePath -Parent |Where-Object {$_} |Test-Path)-eq$false).Count-eq0:-D -
查看
Get-Help Resolve-Path及其返回的属性。
标签: powershell validation