我正在研究一個腳本,它可以在幾十個工作表中輸出大約600個變量,它只需要大約500行代碼將列標題添加到每個工作表。爲了減少大量的整體代碼,我試圖將創建列標題的操作放到函數中,但由於某些原因,set變量不會設置值。當我嘗試在項目中設置子值時,它只會給我一個錯誤。
這將返回以下錯誤
Function PopulateWorkSheet($Worksheet,$Values) {
ForEach ($Value in $Values) {
$ColumnCount++
Set-Variable -Name $($Worksheet).Cells.Items(1,$ColumnCount) -value $Value
}
Remove-Variable -Name ColumnCount
}
錯誤
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
但這並不返回錯誤。
Function PopulateWorkSheet($Worksheet,$Values) {
ForEach ($Value in $Values) {
$ColumnCount++
Set-Variable -Name $($Worksheet) -value $Value
}
Remove-Variable -Name ColumnCount
}
我的全部代碼
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")
不幸的是,使用這種方法使得它認爲變量爲空:/「你不能在空值表達式上調用方法。」 – user1451070
我的壞...我沒有閱讀整個列表。不幸的是這些解決方案的 –