PowerShell: Script Module variables not available outside of ISE -


i have been working on updating of scripts have written. still learning powershell go on old ones , see if can improve things.
stumbled upon modules , idea of using them store different actions can called on @ anytime.

i wrote simple script test (or thought). should mention storing modules on server share.

write-host "testing available variables" write-host "loading modules" import-module <path module on server share>.psm1 write-host "" write-host "done" write-host "print loaded modules" get-module write-host "" write-host "done" write-host "=================" write-host "" write-host "printing variables" write-host "" write-host "variable: arch: " $arch write-host "variable: wownode: " $wownode write-host "" write-host "done" 

my module contained

if ( "${env:programfiles(x86)}" -ne "" )  {     $script:arch = 64     $script:wownode = "\wow6432node\"  }  else  {     $script:arch = 32     $script:wownode = "\"  } 

when run script using windows powershell ise functions how thought would. see contents of variables , print out correctly.
when run script powershell command line window, module gets loaded, variables blank (nothing prints out).
have been digging around google , thing saw maybe causing related scope using define variables.
defining them $script:xx puts them global scope (i'm pretty sure) makes them available throughout script. think defining variables correctly. still haven't had luck.

i missing obvious, life of me can't find it.
suggestions on can troubleshoot issue?
have confirmed running version 2.0 of powershell since read modules available in version 2.0.

from can think of right now(without testing), problem scope say. there difference between running script in ise , in console. i'm guessing when you're running script in ise, open script , press run button. execute script line line in console, if typing them directly console. makes script run in global (session) variable scope. since script in global, module 1 running in script scope.

however, when run script in powershell console; like:

ps > .\myscript.ps1 

then script run in script scope(every variable deleted when script done). now, module run in it's own script scope, below scope mainscript runs in. when module finished being imported, module's script scope deleted, , main script in it's own scope, variables not exist.

global (session)  - script (mainscript)    - script (module)      #module completes, , scope deleted    #you $script:arch , deleted right above.    #powershell searches through mainscript's scope, finds nothing. 

to solve this, try storing values in global (session) scope, $global:arch. specify global scope when create variable(required), , when read it(recommended).


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -