In Python there are simple one liners that can take a path like C:somefoldersomesubfolderfile.csv
, grab the C:somefoldersomesubfolder
part, if it exists, and tell you if it's valid. I have to account for a user potentially passing in an absolute path, a relative path, or no path at all and the file just writing to the same directory. Some potential user input:
..an_invalid_foldersomething.csv
C:
an invalid foldersomething.csv
something.csv
some_absolute_pathsomething.csv
In PowerShell I found this surprisingly cumbersome. I found things like Split-Path have strange behaviors - Ex: if you pass only C:
and then run split path with the leaf option it will tell you C:
is the leaf. Now, I understand why they do that but it makes solving the above a bit ugly. Below is what I came up with - does PowerShell not have something like the os.path
library that more cleanly handles all these situations?
$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 }
question from:
https://stackoverflow.com/questions/66067993/does-powershell-have-a-clean-way-of-validating-a-path-to-a-file-to-be-created 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…