我有一组来自JSON文件的键/值对。
$ $p.dependencies
@architect/architect : ^5.7.0
@architect/functions : ^3.0.4
assert : ^1.4.1
bcrypt : ^3.0.6
find-parent-dir : ^0.3.0
hashids : ^1.2.2
http-status-codes : ^1.3.2
lodash.get : ^4.4.2
mini-web-server : ^1.0.2
mini-webhook-server : ^1.0.4
mocha : ^5.2.0
opencorporates : ^3.0.0
stripe : ^6.23.1
uuid : ^3.3.2
whois-json : ^2.0.4在Powershell中,它们是noteProperty的:
TypeName: System.Management.Automation.PSCustomObject
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
@architect/architect NoteProperty string @architect/architect=^5.7.0
@architect/functions NoteProperty string @architect/functions=^3.0.4
assert NoteProperty string assert=^1.4.1
bcrypt NoteProperty string bcrypt=^3.0.6
find-parent-dir NoteProperty string find-parent-dir=^0.3.0
hashids NoteProperty string hashids=^1.2.2
http-status-codes NoteProperty string http-status-codes=^1.3.2
lodash.get NoteProperty string lodash.get=^4.4.2
mini-web-server NoteProperty string mini-web-server=^1.0.2
mini-webhook-server NoteProperty string mini-webhook-server=^1.0.4
mocha NoteProperty string mocha=^5.2.0
opencorporates NoteProperty string opencorporates=^3.0.0
stripe NoteProperty string stripe=^6.23.1
uuid NoteProperty string uuid=^3.3.2
whois-json NoteProperty string whois-json=^2.0.4我想用@architect/functions ^3.0.4 键将项更改为与^3.0.4(然后将数据保存回来)不同的值
接下来的部分似乎是从哈希表中选择正确的项。我正在使用:
$p.dependencies | where $_.key -eq "@architect/functions"但是,这不会返回任何结果。如何选择带有键@architect/functions**?**的项目作为积分,如何更改值!
编辑:
使用这个答案,这是我的最后一个脚本,如果有人觉得有用的话。
ls 'src/http' | foreach {
$packageJSONFile = "${PSItem}\package.json"
$packageJSON = cat $packageJSONFile | convertfrom-json
if ( $packageJSON.dependencies.'@architect/functions' ) {
$packageJSON.dependencies.'@architect/functions' = '^3.0.4'
}
$packageJSON | ConvertTo-Json -depth 100| set-content $packageJSONFile
} 发布于 2019-04-19 21:44:01
若要获取名称中具有特殊字符的属性,请引用该属性:
$p.dependencies.'@architect/functions'发布于 2019-04-20 03:09:43
Tomalak's helpful answer解决了你的问题。
至于您试图使用where (Where-Object)检索感兴趣的属性:
$p.dependencies | where $_.key -eq "@architect/functions"
有两个基本问题:
key),而不是通过自动变量$_ ($_.key)。- In fact, `$_` - to refer to the pipeline input object at hand - is only ever meaningful _inside a script block_ (`{ ... }`).
- That is, if your command were otherwise correct (it isn't, see below), you'd have to use:$p.dependencies | where key -eq '@architect/functions'
$p.dependencies包含一个[pscustomobject]实例,而不是哈希表([hashtable]);ConvertFrom-Json返回[pscustomobject]实例,除非您使用-AsHashtable开关显式请求哈希表。- If it were a hash table, PowerShell would send it through the pipeline _as a whole_.
- In order to send a hash table's _entries_ one by one through the pipeline, you'd have to call `.GetEnumerator()` on it, which would allow you to filter by their `Key` property.
https://stackoverflow.com/questions/55768097
复制相似问题