gpt4 book ai didi

powershell - 即使未调用,带有PSCustomObjects的数组也会更改值

转载 作者:行者123 更新时间:2023-12-02 23:53:45 25 4
gpt4 key购买 nike

我编写了一个脚本(PowerShell≥3),该脚本主要查找某些文件,然后检查文件的名称是否已在以后将文件复制到的路径中使用,如果是,则在名称中添加_OutCopy。它的作用远不止于此,但这与这个问题无关。

#requires -version 3

Function Start-FileSearch(){
param(
[string]$InputPath = $(throw 'InputPath not set'),
[string]$Format = $(throw 'Format not set')
)
$InFiles = @()
$InFiles = @(Get-ChildItem -LiteralPath $InputPath -Filter $Format -Recurse -File | ForEach-Object {
[PSCustomObject]@{
InFullName = $_.FullName
OutName = "ZYX"
}
})
return $InFiles
}

Function Start-OverwriteProtection(){
param(
[string]$OutputPath = $(throw 'OutputPath not set'),
[array]$InFiles = $(throw 'InFiles not set')
)

$NewFiles = $InFiles

for($i=0; $i -lt $NewFiles.Length; $i++){
$NewFiles[$i].OutName = "$($NewFiles[$i].OutName)_OutCopy" # this, of course, is simplified.
}
return $NewFiles
}

Function Start-AllStuff() {
$InFiles = @(Start-FileSearch -InputPath "D:\Temp\In_Test" -Format "*.jpg")
$InFiles | Format-Table -AutoSize -Property OutName,InFullName | Out-Host

$NewFiles = @(Start-OverwriteProtection -OutputPath "D:\Temp" -InFiles $InFiles)
$InFiles | Format-Table -AutoSize -Property OutName,InFullName | Out-Host
$NewFiles | Format-Table -AutoSize -Property OutName,InFullName | Out-Host
}

Start-AllStuff
显然,第二个 $InFiles | Format-Table也应该输出 "ZYX".OutName-但是,它包括已经更改的值。
我试过的
  • 将所有变量放入private: -scope,
  • 将命令放在第三个函数Start-Allstuff()
  • 的内部/外部
  • 重命名每个用例的变量(即始终使用$InFiles)/不重命名变量(即如上所示,使用$NewFiles)。
  • 创建变量后调用它们(即$InFiles = @(Start-FileSearch [...] ); $InFiles)

  • 没有任何帮助。
    到目前为止,我的理解是,如果不直接调用变量,则不可能更改。 (例如 $InFiles = $OutFiles应该更改左侧的变量,而不是右侧的变量。)
    我在这里想念什么?
    对于每个想知道的人:是的,我进一步研究了 previous question ("Compare-Object does not work with PSCustomObjects from another script")的问题,发现这一定是它不起作用的原因-至少这是原因之一。

    最佳答案

    iRon是正确的,您需要克隆PSObject,下面的代码。

    $NewFiles = $InFiles
    $NewInFiles = $InFiles | select *

    for($i=0; $i -lt $NewFiles.Length; $i++){
    .........................
    $NewFiles = @(Start-OverwriteProtection -OutputPath "D:\" -InFiles $InFiles)
    $NewInFiles | Format-Table -AutoSize -Property OutName,InFullName | Out-Host
    $NewFiles | Format-Table -AutoSize -Property OutName,InFullName | Out-Host

    看起来您的for循环正在修改$ InFiles,请查看我的结果。经过随机图像测试。

    $Infiles outside For loop

    $Infiles inside For loop

    关于powershell - 即使未调用,带有PSCustomObjects的数组也会更改值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51082199/

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