gpt4 book ai didi

powershell - 静态的PowerShell对象

转载 作者:行者123 更新时间:2023-12-03 00:24:50 31 4
gpt4 key购买 nike

我可以创建一个类似于$x = Get-Process的引用,然后可以使用$x进行调用。太好了,每次我键入$x时,过程都会更新,但是对于我正在做的事情,我并不希望如此。我想在某个时间点捕获过程的快照,然后能够查询该捕获点在该时间点的所有属性。

因此,我正在寻找一种声明$x的方法,以便在调用时收集所有内容,然后在我引用$ x时,它包含该时间点的历史值,而无需重新处理Get-Process。我该怎么办?

最佳答案

看起来您想要的是克隆对象。
为此,有一种简单的方法:$y = $x | Select-Object *,但这并不总是足够的,因为它将使您的副本很浅。

为了能够进行深拷贝,您可以尝试以下功能:

function Clone-Object ([object]$obj, [switch]$DeepClone) {
if ($DeepClone) {
# create a deep-clone of an object
# test if the object implements the IsSerializable Interface
if ([bool]($obj.GetType().IsSerializable)) { # or: if ([bool]($obj.GetType().Attributes -band 'Serializable')) {
$ms = New-Object System.IO.MemoryStream
$bf = New-Object System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
$bf.Serialize($ms, $obj)
$ms.Position = 0
$clone = $bf.Deserialize($ms)
$ms.Close()
}
else {
# try PSSerializer that serializes to CliXml
# source: https://stackoverflow.com/a/32854619/9898643
try {
$clixml = [System.Management.Automation.PSSerializer]::Serialize($obj, 100)
$clone = [System.Management.Automation.PSSerializer]::Deserialize($clixml)
}
catch {
Write-Error "Could not Deep-Clone object of type $($obj.GetType().FullName)"
}
}
}
else {
# create a shallow copy of the same type
# if the object has a Clone() method
if ($obj -is [System.ICloneable]) {
$clone = $obj.Clone()
}
# test if the object implements the IEnumerable Interface
elseif ($obj -is [System.Collections.IEnumerable]) {
try {
# this only works for objects that have a parameter-less constructor
$clone = New-Object -TypeName $($obj.GetType().FullName) -ErrorAction Stop
foreach ($pair in $obj.GetEnumerator()) { $clone[$pair.Key] = $pair.Value }
}
catch {
Write-Error "Could not Clone object of type $($obj.GetType().FullName)"
}
}
# not Cloneable, not Enumerable..
else {
# this returns an object with the properties copied,
# but it is NOT OF THE SAME TYPE as the source object
$clone = $obj | Select-Object *
}
}

return $clone
}

像这样使用它:
$y = Clone-Object $x -DeepClone

希望能有所帮助

关于powershell - 静态的PowerShell对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59371770/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com