简体   繁体   English

在循环中使用Set-Variable设置子值(例如$ Myvar.item.value)的问题

[英]Issues using Set-Variable to set sub values (ex. $Myvar.item.value) in loop

I am working on a script that outputs about 600 variables across several dozen worksheets and it takes up about 500 lines of code just to add the column headers to each of the worksheets. 我正在处理一个脚本,该脚本在几十个工作表中输出大约600个变量,并且仅将列标题添加到每个工作表中就需要大约500行代码。 In an effort to reduce the immense amount of overall code I am trying to put the action of creating the column headers to a function but for some reason set-variable won't set the value. 为了减少大量的整体代码,我试图将创建列标题的操作放到一个函数中,但是由于某种原因,set-variable不会设置该值。 It only gives me an error when I try and set sub values in the item. 当我尝试在项目中设置子值时,它只会给我一个错误。

This returns the following error 这将返回以下错误

Function PopulateWorkSheet($Worksheet,$Values) {
    ForEach ($Value in $Values) {
        $ColumnCount++
        Set-Variable -Name $($Worksheet).Cells.Items(1,$ColumnCount) -value $Value
    }
    Remove-Variable -Name ColumnCount
}

Error 错误

You cannot call a method on a null-valued expression.
At line:4 char:30
+         Set-Variable -Name $($Worksheet).Cells.Items(1,$ColumnCount) -value $Val ...
+                              ~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

But this doesn't return an error. 但这不会返回错误。

Function PopulateWorkSheet($Worksheet,$Values) {
    ForEach ($Value in $Values) {
        $ColumnCount++
        Set-Variable -Name $($Worksheet) -value $Value
    }
    Remove-Variable -Name ColumnCount
}

My Full Code 我的完整代码

Function PopulateWorkSheet($Worksheet,$Values) {
    ForEach ($Value in $Values) {
        $ColumnCount++
        Set-Variable -Name $($Worksheet).Cells.Items(1,$ColumnCount) -value $Value
    }
    Remove-Variable -Name ColumnCount
}

clear
#Create Excel Com Object
$Excel = New-Object -com Excel.Application

# Make the Excel Application Visible to the end user
$Excel.visible = $True

# Create a WorkBook inside the Excel application
# that we can start manipulating.
$Excel_Workbook = $Excel.Workbooks.Add()

#=======================================================
# Now that we have a workbook we need to create some
# additional worksheets (Tabs) beyond that initial 3
# that are created when the workbook is opened.
#=======================================================
$Temp_MakeWorkSheet = $Excel.Worksheets.Add()

#=======================================================
# Once all the sheets are created each of the worksheets
# need to be assigned to a variable so they can be
# manipulated.
#=======================================================
$Excel_Worksheet_SystemSummary = $Excel.Worksheets.Item(1)
$Excel_Worksheet_SystemSummary.Name = "System Summary"

#=======================================================
# = System Summary = Create Table Headers
#=======================================================

PopulateWorkSheet -Worksheet Excel_Worksheet_SystemSummary -value @("Computer Name","Serial Number","Operating System","Service Pack","OS Architecture","Part of Domain","Domain Role","System Uptime","IP Address","OS HD Smarts Check","# of Mice","# of Keyboards","# of Hard Drives","# of CD/DVD Drives","# of Network Adapters")

Why do you think you need to use Set-Variable at all? 为什么您认为根本需要使用Set-Variable Set-Variable is for setting Powershell variables when you don't know the name in advance, or when you want to do special things like making them read-only. Set-Variable用于在您事先不知道名称或想要执行特殊操作(例如将其设置为只读)时设置Powershell变量。 In this case you don't want to set a Powershell variable at all, you want to set the value of a cell in a worksheet. 在这种情况下,您根本不需要设置Powershell变量,而是要在工作表中设置单元格的值。

So forget Set-Variable . 所以忘了Set-Variable Also forget Remove-Variable : returning from a function removes all the local variables anyway, you don't have to do it yourself. 还要忘了Remove-Variable :从函数返回仍然会删除所有局部变量,您不必自己做。

$Worksheet , if I read your code correctly is simply a reference to the worksheet. $Worksheet ,如果我正确阅读了您的代码,仅是对工作表的引用。 So why did you write $($Worksheet) ? 那你为什么写$($Worksheet) That doesn't actually do anything that just writing $Worksheet wouldn't have done on its own. 实际上,这并没有完成仅编写$Worksheet本身不会做的任何事情。

Now consider $Worksheet.Cells.Items(1,$ColumnCount) . 现在考虑$Worksheet.Cells.Items(1,$ColumnCount) The first two elements won't change inside your loop, so hoist them out of the loop. 前两个元素不会在循环内更改,因此请将其从循环中提升。 Now you should have something like: 现在,您应该具有以下内容:

Function PopulateWorkSheet($Worksheet,$Values) {
    $cells = $Worksheet.Cells
    $ColumnCount = 0
    ForEach ($Value in $Values) {
        $ColumnCount++
        $cells.Item(1,$ColumnCount) = $Value
    }
}

This also works: 这也适用:

Function PopulateWorkSheet($Worksheet,$Values) {
    $Worksheet.Range(
        $Worksheet.Cells.Item(1,1),
        $Worksheet.Cells.Item(1,$Values.Count)).value() = $Values
}

and will assign the complete list in one go. 并一次性分配完整列表。

Instead of 代替

Set-Variable -Name $($Worksheet).Cells.Items(1,$ColumnCount) -value $Value

Try 尝试

$var=Get-Variable -Name $($Worksheet)
$var.Cells.Items(1,$ColumnCount)=$Value

Note...I haven't tried this, but there's no reason it shouldn't work. 注意...我还没有尝试过,但是没有理由不起作用。

So I was way overthinking it. 所以我想得太多了。 I did not need to try and load the variable in the function, but pass value to the "Worksheet" variable since the $Excel_Worksheet_SystemSummary is just a link to the cell contents, and it doesn't actually hold any real information. 我不需要尝试在函数中加载变量,而是将值传递给“ Worksheet”变量,因为$ Excel_Worksheet_SystemSummary只是指向单元格内容的链接,并且实际上不包含任何实际信息。

Function PopulateWorkSheet($Worksheet,$Values) {
    ForEach ($Value in $Values) {
        $ColumnCount++
        $worksheet.Cells.Item(1,$ColumnCount)=$Value
    }
    Remove-Variable -Name ColumnCount
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法使用Set-Variable设置变量的Description属性 - Unable to set Description property of a variable using Set-Variable 如何在PowerShell中使用Set-Variable声明全局变量? - How to declare global variable using Set-Variable in PowerShell? 将$ myVar设置为带通配符的变量 - Set $myVar as a variable with wildcard Set-Variable foo -Scope Global -Value“bar”和$ global:foo =“bar”之间的区别 - Difference between Set-Variable foo -Scope Global -Value “bar” and $global:foo = “bar” 在 Powershell 中设置变量不覆盖脚本参数? 尝试使用 JSON 读取 JSON 并覆盖脚本参数 - In Powershell set-variable not overriding Script Parameters? Trying to read JSON and override script parameters using JSON Powershell Set-Variable 重置变量而不是更新它 - Powershell Set-Variable resets Variable instead of updating it PowerShell 中的“$myvariable =”和 Set-Variable 有什么不同? - What's different between "$myvariable =" and Set-Variable in PowerShell? Azure DevOps 条件无法评估 Powershell 设置变量 - Azure DevOps conditional can't evaluate Powershell set-variable 集变量Powershell。 如何将变量链接到exe文件? - Set-Variable powershell. How do I link a variable to an exe file? 使用for循环列表并将元素设置为环境变量然后获取值 - Use a for loop for list and set element to environment variable then get value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM