Author Posts

February 26, 2018 at 5:14 am

HELLO PEOPLE,

I HAVE ONE PROBLEM WHILE USING POWERSHELL. SOMETHING STRANGE HAPPENS. AND THIS IS THAT POWERSHELL DOES NOT WANT TO LOAD CLASS I WROTE. BUT ONLY IF I TRY TO LOAD IN POWERSHELL.EXE. IF I TRY TO LOAD IN POWERSHELL_ISE.EXE, IT WORKS.
HERE IS ONE EXAMPLE:
IF I OPEN POWERSHELL_ISE.EXE AND CREATE NEW SCRIPT, FOR EXAMPLE TEST.PS1, AND I WRITE INTO SCRIPT FOR EXAMPLE:

CLASS TEST {}

AND THEN IF I SAVE THIS SCRIPT, AND AFTER THAT TRY TO RUN FOLLOWING COMMANDS IN POWERSHELL_ISE:

TEST.PS1;
[TEST]::NEW();

EVERYTHING WORKS OKAY.

BUT THE PROBLEM IS THAT IF I OPEN POWERSHELL AND RUN EXACT SAME COMMANDS IN IT:

TEST.PS1;
[TEST]::NEW();

IT DOES NOT WORK, BUT INSTEAD COMPLAINS THAT TYPE TEST IS NOT DEFINED.

THIS IS ODD, SINCE IT WORKS IN POWERSHELL_ISE. AND IT SHOULD WORK SINCE I RUN TEST.PS1; LINE WHICH SHOULD DEFINE NEW TYPE [TEST]. I SAW ON INTERNET EXAMPLES OF PEOPLE CLAIMING THAT IT WORKS IF YOU USE USING MODULE COMMAND AND IF YOU SAVE CLASS DEFINITION INTO .PSM1 FILE.
SO, I HAVE TRIED RENAMING SCRIPT TO BE TEST.PSM1 AND THEN RUNNING:

USING MODULE TEST.PSM1;
[TEST]::NEW();

BUT STILL, I GET THE SAME ERROR. POWERSHELL SIMPLY DOES NOT SEE CLASS DEFINED IN TEST FILE.

SO, MY QUESTION IS, IS THIS NORMAL, OR SOMETHING IS WRONG WITH MY POWERSHELL? SINCE ON INTERNET I SEE PEOPLE SAYING IT WORKS.

OR, SHOULD I DO SOMETHING DIFFERENT IN ORDER FOR IT TO WORK?

FOR ANY POTENTIAL REPLYS, THANK YOU.
BYE

February 26, 2018 at 2:01 pm

Starting ISE

create a class

class test {
[int]$P1 = 1
[int]$p2 = 2

}

Run the code

you can create an instance of the class in the ISE Script pane
PS> [test]::new()

P1 p2
— —
1 2

Now save the code as test.ps1.
Run the code in the console

PS> .\test.ps1
PS> [test]::new()
Unable to find type [test].
At line:1 char:1
+ [test]::new()
+ ~~~~~~
+ CategoryInfo : InvalidOperation: (test:TypeName) [], RuntimeException
+ FullyQualifiedErrorId : TypeNotFound

The reason you're not seeing [test] is that a script runs in its own scope and all variables, functions classes etc are removed at the end of the script's execution.

You need to dot source the script so that the class remains in memory. You do that by putting a . in front of the script name like this

PS> . .\test.ps1
PS> [test]::new()

P1 p2
— —
1 2

March 1, 2018 at 1:23 am

HELLO RICHARD,

THANK YOU VERY MUCH FOR CLARIFYING THIS TO ME.
I AM SORRY, THIS WAS MY BAD. I GUESS I MISSED PART ABOUT DOT SOURCING WHEN I WAS STUDYING POWERSHELL.

THANK YOU.