【发布时间】:2020-08-12 07:55:08
【问题描述】:
我在 Windows 7 下使用 Powershell 4,并且我的 cmdlet 定义如下:
Function Transfer-File {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[System.Management.Automation.PSCustomObject]
$source,
# other parameters removed for brevity
)
# actual logic does not matter
}
我这样称呼它:
$hasError = Transfer-File -source $source -destination $cfg.Destination -logfile $logFile
$source是通过解析一个JSON文件得到的,看起来是这样的:
@{Path=some path string here; Pack=False}
Write-Host $source.GetType() 输出:
System.Management.Automation.PSCustomObject
我收到以下错误:
无法转换“@{Path=some path string here; Pack=False}” 要键入的“System.Management.Automation.PSCustomObject”类型的值 “System.Management.Automation.PSCustomObject”。
在绝望的尝试中,我将System.Management.Automation.PSCustomObject 替换为psobject,它似乎工作正常。
问题:为什么我的 System.Management.Automation.PSCustomObject 似乎不适合 cmdlet 原型中的 System.Management.Automation.PSCustomObject?
对象创建的完整代码:
### Configuration ###
$cfg = New-Object –TypeName PSObject
$cfg | Add-Member -MemberType NoteProperty –Name Sources –Value @()
# get configuration from json file
$jsonContent = Get-Content .\config.json | Out-String
$jsonObj = ConvertFrom-Json $jsonContent
$cfg.Sources = $jsonObj.Sources
Foreach ($source in $cfg.Sources)
{
# Write-Host $source.GetType()
$hasError = Transfer-File -source $source -destination $cfg.Destination -logfile $logFile
}
【问题讨论】:
-
您是如何创建
$source对象的?通过New-Object? -
[System.Management.Automation.PSCustomObject]是一个单例对象,它的实例用来表示[System.Management.Automation.PSObject]中没有有意义的基础对象。
标签: powershell type-conversion powershell-4.0 powershell-cmdlet