如果我正在编写"惯用"PowerShell,我将使用哪些参数类型来处理与文件或目录一起使用的函数?
例如,我创建了一个包含此功能的模块:
$bookmarks = @{}
$bookmarkKeys = @{}
function Set-Bookmark {
param(
[Parameter(Mandatory = $true)]
[string] $Id,
[System.Management.Automation.DirectoryInfo] $Path = (Get-Location))
$script:bookmarks[$Id] = $Path
$script:bookmarkKeys[$Path.Path] = $Id
}
Run Code Online (Sandbox Code Playgroud)
麻烦的是,以下不起作用:
PS>Set-Bookmark -Id Code -Path C:\Code
Set-Bookmark : Cannot process argument transformation on parameter 'Path'.
Cannot convert the "C:\Code" value of type "System.String" to type
"System.Management.Automation.PathInfo".
At line:1 char:29
+ Set-Bookmark -Id Code -Path C:\Code
+ ~~~~~~~
+ CategoryInfo : InvalidData: (:) [Set-Bookmark], ParameterBindingArgumentTransformationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,Set-Bookmark
Run Code Online (Sandbox Code Playgroud)
很奇怪,这也不是(但原因略有不同):
PS>Set-Bookmark -Id Code -Path (gi C:\Code)
Set-Bookmark : Cannot process argument transformation on parameter 'Path'.
Cannot convert the "C:\Code" value of type "System.IO.DirectoryInfo" to type
"System.Management.Automation.PathInfo".
At line:1 char:29
+ Set-Bookmark -Id Code -Path (gi C:\Code)
+ ~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Set-Bookmark], ParameterBindingArgumentTransformationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,Set-Bookmark
Run Code Online (Sandbox Code Playgroud)
那么我应该将我的参数实际定义为字符串(即最小公分母)然后尝试将它们转换/解析为更有意义的类型吗?这听起来不对,因为如果我正在使用类似的结果Get-Item并且它们被归结string为传入,那么这是一种耻辱,只有该功能才能再次解析为更高级别的类型.
我认为你想使用 type [IO.DirectoryInfo]。这对我来说效果很好:
function t {
param(
[IO.DirectoryInfo] $d
)
"You passed $d"
}
t (Get-Item "C:\Windows")
Run Code Online (Sandbox Code Playgroud)
对于文件,您可以使用[IO.FileInfo],尽管这不支持通配符。
| 归档时间: |
|
| 查看次数: |
1034 次 |
| 最近记录: |