The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

StephenD (3) [Avatar] Offline
#1
Hello,

I am just beginning with this shell, and there is something I'd like an explanation for.
A lot of my work involves dealing with software revisions, so it's tremendous that I can take an array of file names and check the installed versions of these.

I want to automate this by using a reference file to create an array and then comparing those elements with installed software. Here's the scenario:
I have a file - c:myscriptsdll.csv - with x PATHFILE specifications.

C:windowssystem32asesrv.dll
C:windowssystem32atmeter.dll

In the shell, I do the following:
PS C:MyScripts> $newarray = new-object system.collections.arraylist
PS C:MyScripts> get-content c:myscriptsdll.csv | foreach {$newarray.add($_)}
0
1
PS C:MyScripts> $newarray
C:windowssystem32asesrv.dll
C:windowssystem32atmeter.dll

So far, so good. I don't care about the errant output for now. However I want to automate the creation of the array, so I create a function in the shell.....

PS C:MyScripts> Function ImportToNewArray($a)
>> {
>> $newarray = new-object system.collections.arraylist
>> get-content $a | foreach {$newarray.add($_)}
>> }
>>
PS C:MyScripts> ImportToNewArray c:myscriptsdll.csv
0
1
PS C:MyScripts> $newarray <---- calling it here works
C:windowssystem32asesrv.dll
C:windowssystem32atmeter.dll

This works in the shell, but after I've stored this function in my profile and call it I get a different result:
(I've closed and restarted the shell here)
PS C:MyScripts> ImportToNewArray c:myscriptsdll.csv
0
1
PS C:MyScripts> $newarray <----- calling it here returns nothing
PS C:MyScripts>

Can someone explain why this is behaving like this?

Thanks,

Stephen
P.S. I really am enjoying the Powershell.
PeterJ (83) [Avatar] Offline
#2
Re: ... Where did my array go?
Go back and read section 7.6.3, Scopes and Scripts. The $newarray in your script is a variable local to the script. The $newarray from the command line has a more global scope. You can't access a script variable after the script exists because it no longer exists. But if you want the $newarray in your script to be accessible from the command line, use $global:newarray within the script instead.

Message was edited by:
PeterJ
StephenD (3) [Avatar] Offline
#3
Re: ... Where did my array go?
Thank you Peter, that works fine.
Time to take my nose back to the book.

StephenD