我最近开始用powershell 5创建类.当我关注这个很棒的指南时https://xainey.github.io/2016/powershell-classes-and-concepts/#methods
我想知道是否有可能覆盖get_x和set_x方法.
例:
Class Foobar2 {
[string]$Prop1
}
$foo = [Foobar2]::new()
$foo | gm
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
Prop1 Property string Prop1 {get;set;}
Run Code Online (Sandbox Code Playgroud)
我想这样做是因为我认为除了使用我的自定义Get和Set方法之外,其他人访问属性会更容易:
Class Foobar {
hidden [string]$Prop1
[string] GetProp1() {
return $this.Prop1
}
[void] SetProp1([String]$Prop1) {
$this.Prop1 = $Prop1
}
}
Run Code Online (Sandbox Code Playgroud) 我需要与需要JSON帖子数据的REST API进行交互.所以我开始使用这样的东西:
$ReqURI = 'http://httpbin.org/post'
Invoke-WebRequest -Method Post -Uri $ReqURI -Body @{
'api.token' = "api.token"
'action' = 'create item'
} -Verbose| fl *
Run Code Online (Sandbox Code Playgroud)
所以我用httpbin.org测试了它:
但是,如果您需要在正文部分中使用列表或数组,如下例所示:
$ReqURI = 'http://httpbin.org/post'
$Response = Invoke-RestMethod -Method Post -Uri $ReqURI -Body @{
'api.token' = "api.token"
'names' = @('rJENK', 'rFOOBAR')
} -Verbose| fl *
$Response
Run Code Online (Sandbox Code Playgroud)
...你得到的东西就像转换错误:
所以我想我可以将自己转换为JSON字符串并使用-Depth参数from ConvertTo-JSON.除此之外,我尝试了如果我先将哈希表转换为对象的样子.
但两次尝试都会返回相同甚至更糟的结果:
所以最后我切换到了Invoke-WebRequest.但这里的结果是一样的.
我的参考是使用JSON字符串的工作api调用:
"api.token" : "fooobar",
"names": [
"rJENK",
"rFOOBAR"
]
Run Code Online (Sandbox Code Playgroud)
我想出了一个解决方法.看起来我正在使用的api无法处理包含嵌套元素或PowerShell创建的数组的请求.
非工作示例:
$ReqURI = 'http://httpbin.org/post'
$Response = Invoke-RestMethod …Run Code Online (Sandbox Code Playgroud) 我尝试在类方法中使用预定义的变量,如 $PSVersionTable 或 $PSScriptRoot。他们失败并显示错误消息
方法中未分配变量。
例子:
Class Foo {
[String]$Version
GetVersion() {
If ($PSVersionTable) {
$this.Version = $PSVersionTable.PSVersion
}
}
}
Run Code Online (Sandbox Code Playgroud)
但为什么?