|
Re: Include another script, keep variables in included script? Hi Kryten,
Suppose you have your IPs in 'c:\ips.txt' and the sample scripts are all in 'c:\'. 'scriptA.ps1' resolves the hostname for each IP and outputs it to a text file in a two-column format. 'scriptA.ps1' also lets you import variables from it to the caller's scope by using the -ExportVariable switch and by passing the variable name(s) to its -VariableName parameter. Note that both parameters are declared last in the Param declaration and the output file is not generated when exporting variables, this last is optional, you can remove the exit statement and 'scriptA.ps1' will generate the output file. 'scriptB.ps1' calls 'scriptA.ps1' and 'imports' variable $col.
-< scriptA.ps1 >-
param(
[string[]]$ips,
[string]$outFile,
[switch]$exportVariable,
[string[]]$variableName
)
$col = $(
foreach ($ip in $ips) {
trap [formatException] {
sv hostName 'Invalid IP' -s 1
continue
}
trap [net.sockets.socketException] {
sv hostName 'No data found' -s 1
continue
}
$hostName = [net.dns]::getHostByAddress($ip).hostName
$obj = new-object psObject
$obj | add-member noteProperty IP $ip -p |
add-member noteProperty HostName $hostName -p
}
)
if ($exportVariable -and $variableName) {
foreach ($var in $variableName) {
set-variable $var (gv $var).value -scope 1
}
# optional: exit the script, no output file generated
exit
}
$col | ft -a | out-string -s | ? {$_} > $outFile
-< scriptA.ps1 >-
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
-< scriptB.ps1 >-
# calls scriptA using the -ExportCollection switch and specifies the
# variables you want to export
c:\scriptA (gc c:\ips.txt) -export -var col
# $col is available
$col | ft HostName
-< scriptB.ps1 >-
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
-< scriptC.ps1 >-
# calls scriptA w/o importing variables
c:\scriptA (gc c:\ips.txt) c:\out.txt
-< scriptC.ps1 >-
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
Try this:
@'
128.183.240.121
--
207.46.19.254
72.246.25.89
55.55.55.55
69.17.117.207
208.80.152.2
'@ > c:\ips.txt
gc c:\ips.txt
c:\scriptB
c:\scriptC
gc c:\out.txt
--
Kiron |