Powershell - Store function output in variable not working - function

stuck at this one trying to store function output in a variable:
function AD-prompt($Text)
{
do
{
$in = read-host -prompt "$Text"
}
while($in -eq "")
}
calling the function with
$type = AD-prompt "Sample Text"
does not store anything in $type - only when i remove the entire do-while loop it works. it seems the function output is empty as the read-host output is stored in the $in variable, but i have no idea how to solve this - i didnt find another way to loop the read-host aswell sadly.

You need to return $in from your function by outputting it. You can do this by putting it on a line on its own after your loop:
function AD-prompt($Text)
{
do
{
$in = read-host -prompt "$Text"
}
while($in -eq "")
$in
}

Related

How to handle the result of a Powershell Object to call a function

Here is my code:
function setParameterb () {
$Name = $args[0]
"Arg1: $Name"
}
Write-Output "### Starte AlertlogRotate ###"
$folders = #('d:', 'e:', 'f:', 'g:', 'h:', 'i:', 'j:', 'k:', 'l:')
foreach ($i in $folders) {
$filenames = Get-ChildItem -Path $i\*\log -ErrorAction SilentlyContinue -Recurse -Filter alert_*.log | Select-Object FullName
}
The setParametersb function is just for test now and should only print the result. Later, I will use it to zip logfiles which get too big.
I need to get the result of this powershell object into a string to call a function for every line.
The Object looks like this:
FullName
--------
D:\AREA\log\diag\rdbms\area\area\trace\alert_area.log
D:\CONS\log\diag\rdbms\cons\cons\trace\alert_cons.log
D:\DEV01\log\diag\rdbms\dev01\dev01\trace\alert_dev01.log
G:\TEST01\LOG\diag\rdbms\test01\test01\trace\alert_test01.log
G:\TEST02\log\diag\rdbms\test02\test02\trace\alert_test02.log
I know, that I have to crop the headline "FullName", the row"--------" and some empty lines, but this is not my problem now.
My problem is to transfer the object $filenames into an array to be able to call the function setParameterb with every single line from the output.
tried lots of other stuff, but finally this solved my problem:
$filenames |ForEach-Object { setParameterb $_.FullName }
try stuff like
function setParameterb () {
param (
[Parameter(Mandatory=$true)]
$names,
)
foreach($name in $names){
"Arg1: $name"
}
}

What am I doing wrong on PowerShell function parameters?

I would really appreciate it if somebody could point out what I am doing wrong in passing parameters from a function back to the mainline code. I have a variable which has been successfully extracted in a function, but I cannot seem to pass that back to the mainline code
This is the code I am using:
function get-field ($field, $heading) {
$fieldPos = $script:source.AllElements.InnerText.IndexOf($heading) +1
$field = $script:source.AllElements.InnerText[$fieldPos]
# If states "Not Available", or contains a heading, process as if not found.
if ($field -eq "Not Available ") {$fieldPos = 0}
if ($field -eq $heading) {$fieldPos = 0}
# Check that a valid entry was received
if ($fieldPos -eq 0) {
Write-Host "Warning:" $heading "was not found"
} else {
$field = $field.Trim()
}
return $field
}
get-field $email "Name"
get-field $address "Address"
I have verified that within the function, the $field and $heading parameters contain the correct information, so why aren't the $email and $address fields being populated?
You're not doing it totally wrong.
Have a look at this example:
function get-field ($field, $heading) {
return "$field - $heading"
}
$address = get-field "AddressFiled" "AddressHeading"
$address
to catch the returned value in a variable for further use, you should call the function like in the above example.
Parameters in PowerShell are normally used for passing values into a function. The output of a function must be assigned to a variable in the statement that invokes the function. Also, it's bad design to use global variables inside a function, because that makes debugging significantly more difficult.
Your code should look somewhat like this:
function Get-Field ($data, $heading) {
$fieldPos = $data.IndexOf($heading) + 1
$field = $data[$fieldPos].Trim()
# If states "Not Available", or contains a heading, process as if not found.
if ($field -eq 'Not Available' -or $field -eq $heading) {
Write-Host "Warning: ${heading} was not found"
}
$field
}
$email = Get-Field $script:source.AllElements.InnerText 'Name'
$address = Get-Field $script:source.AllElements.InnerText 'Address'
You can have out parameters if you want to, but they're rather uncommon in PowerShell, probably because they're not as straight-forward to use as one would like.
function Get-Field ([ref]$field, $data, $heading) {
$fieldPos = $data.IndexOf($heading) + 1
$field.Value = $data[$fieldPos].Trim()
# If states "Not Available", or contains a heading, process as if not found.
if ($field -eq 'Not Available' -or $field -eq $heading) {
Write-Host "Warning: ${heading} was not found"
}
}
$email = $null
Get-Field ([ref]$email) $script:source.AllElements.InnerText 'Name'
$address = $null
Get-Field ([ref]$address) $script:source.AllElements.InnerText 'Address'

PowerShell adds other values to return value of function

It seems that PowerShell adds an additional variable to the return value of a function.
The function subfoo2 itself delivers the correct values, but as soon as PowerShell jumps back to the postion where I called the function (in foo1), value contains the value of an other variable ($msg)
(Have a look at the comments in the code)
writeMessageLog($msg){
...
Add-Content $msg
...
}
subfoo2{
writeMessageLog($msg)
return $UserArrayWithValues #During Debug, $Array is fine (1)
}
foo1{
$var = subfoo2 $UserArray # $var has now the value of $msg and $UserArrayWithValues (2)
#do something with var
}
Realcode:
function WriteLog
{
param ( [string] $severity , $msgNumber, [string] $msg )
...
$msgOut = $date + ... + $msg
Add-Content $msgout ( $msgOut )
...
}
function getFeatures
{
writelog 'I' 1002 $true $true "Load Features"
$Features = importCsv -pPath $FeatureDefintionFilePath
Writelog 'I' 1000 $true $true "Features Loaded"
return $Features # $Features has value as expected (1)
}
function GetUserFeatures ($pUserObject)
{
$SfBFeatures = ""
$SfBFeatures = getFeatures #SfBFeaures has Value of $msg and $Features (2)
...
}
Do I use the functions/return values wrong? What could lead to such behavior? Is it an issue if i call a function within a function?
If I remove $msgOut = $date + ... + $msg in writeMessageLog, the values are fine.
I'm pretty lost right now, and have no ideas where this comes from. Any ideas welcome.
This is how powershell works, basically everything that you print out will be returned as the function output. So don't output extra stuff. To force something to not output stuff you can do:
$null = some-command_that_outputs_unwanted_things
since everybody is obsessed with Out-Null I'll add this link showing several other ways to do that.
Within a function, everything you don't assign or pipe to a consuming cmdlet will get put to the pipeline and returned from the function - even if you don't explicit return it. In fact the return keyword doesn't do anything in PowerShell so the following is equivalent:
function Test-Func
{
"Hello World"
}
function Test-Func
{
return "Hello World"
}
So it looks like your writeMessageLog puts anything on the pipeline thus you have to either assign the value to anything:
$notUsed = writeMessageLog($msg)
or (prefered) pipe it to the Out-Null cmdlet:
writeMessageLog($msg) | Out-Null

Powershell parameter passing to function

I'm facing with an annoying problem: my script seemingly doesn't pass any argument to a function I've defined.
$server = 'http://127.0.0.1:8080'
Function Get-WorkingDirectory([string]$address)
{
#echo $address
$content = Get-Content -path C:\....\file.txt
$content -contains $address
} #end Get-WorkingDirectory function
if(Get-WorkingDirectory $server)
{
echo "works"
}
else
{
echo "error"
}
It is stuck on "works". If I try to echo address in the function, it is empty.
What the heck I'm doing wrong?! I know this is a pretty noobish question, but I tried everything I found on the net.
Thanks in advance for help!
echo is an alias for Write-Output but as you are using the output of the function in the if statement, nothing gets shown.
For testing purposes, use Write-Host in this instance to show the variable being passed correctly.
$server = 'http://127.0.0.1:8080'
Function Get-WorkingDirectory([string]$address)
{
write-host "$address using write host"
} #end Get-WorkingDirectory function
if (Get-WorkingDirectory $server) {
}
Output of Get-WorkingDirectory is shadowed by if statement.
Try to use it without if and you'll see that argument is passed correctly. For example,
$server = 'http://127.0.0.1:8080'
Function Get-WorkingDirectory([string]$address)
{
Write-Host $address
}
Get-WorkingDirectory $server
Address is printed well

Powershell Functions with multiple params

I am attempting to write a function to compress files using 7zip, but I am having issues passing multiple parameters to the function.
$In = "C:\test\gateways_25357_20140407000204.pcap"
$Out = "C:\test\gateways_25357_20140407000204.zip"
function CompressFile([string]$Output,[string]$Input) {
Write-Host $Output
write-host $Input
$7zipPath = "C:\Program Files\7-Zip\7z.exe"
$Arguments = "a","-tzip",$Output,$Input
& $7zipPath $Arguments
}
CompressFile $Out $In
My results of this code is the compressing of the files in the working directory of this script and the output goes to the correct location c:\test.
What exactly am I doing wrong here with passing in the $Input parameter?
$Input is a powershell automatic variable, try changing the name.
see
$In = "C:\test\gateways_25357_20140407000204.pcap"
$Out = "C:\test\gateways_25357_20140407000204.zip"
function CompressFile([string]$Outputz, [String]$Inputz) {
Write-Host $Outputz
write-host $Inputz
}
Write-Host $Out
write-host $In
CompressFile $Out $In
http://technet.microsoft.com/en-us/library/hh847768.aspx