如何在PowerShell中没有任何预定义路径的情况下读取文件输入? [英] How can I read file input without any pre-defined path in PowerShell?

查看:207
本文介绍了如何在PowerShell中没有任何预定义路径的情况下读取文件输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有用户提供输入txt文件作为参数 -InputFile 我存储为 $ inputfile 。但是当我尝试:

I have users provide an input txt file as an argument -InputFile which I store as $inputfile. But when I try:

$reader = [System.IO.File]::OpenText("$inputfile")

PowerShell会自动将 $ inputfile 路径附加到C: \Windows\system32。如何让PowerShell不假设路径前缀,因此用户只需传递 -InputFile inputfile.txt ,如果他们想要的文件位于运行它们的同一目录中脚本?我如何支持它们枚举一个完全不同的文件路径,如果它在当前目录之外而没有自动附加到C:\ Windows \ system32?

PowerShell automatically appends the $inputfile path to C:\Windows\system32. How can I have PowerShell not assume a path prefix, so a user could simply pass -InputFile inputfile.txt if the file they want is in the same directory from which they run the script? How can I also support them enumerating a completely different path to the file if it's outside of the current directory without having it automatically append to C:\Windows\system32?

编辑:根据您的建议将变量$ input更改为$ inputfile。

Changed the variable "$input" to "$inputfile" per your advice.

推荐答案

使用 Resolve-Path 用于解析在将其传递给 OpenText()之前/之后的路径

$reader = [IO.File]::OpenText((Resolve-Path $InputFile).Path)

由于 Resolve-Path 在无法解析您可能想要运行的路径时抛出异常这在 try..catch 块中,例如像这样:

Since Resolve-Path throws an exception when it can't resolve a path you may want to run this in a try..catch block, e.g. like this:

try {
    $path = (Resolve-Path $InputFile).Path
    $reader = [IO.File]::OpenText($path)
} catch [Management.Automation.ItemNotFoundException] {
    # cannot resolve path
} catch {
    # other error
}

或者更好的是,验证参数:

or, better yet, validate the parameter:

[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[ValidateScript({Test-Path -LiteralPath $_ -Type Leaf})]
[string]$InputFile

这篇关于如何在PowerShell中没有任何预定义路径的情况下读取文件输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆