Output not displayed when assigning the return value of a function to a variable - windows

If I have a very simple script that contains a function that just does the following:
function saySomething() {
Write-Output "Saying someting..."
}
If I call this function from the console the output is displayed. If I, however, do the following:
$something = saySomething
Then no output is displayed. Obviously my working example is much more complicated than this, but in short, how do I display the output within a function if that function is used to set a variable?

Try the following:
saySomething | Tee-Object -Variable something
This should work exactly as you want.

Related

Piping Powershell multiple functions together

I have this going on
Function A($data){
#Function accepts $data which is Get-Content of a file
#Function does some stuff and then return
#Function return data as String
}
Function B($data){
#This Function takes data given from Function A, manipulate it and return custom object
}
$Function C ($data1, $data2){
#This function Takes 2 custom objects created from Function B and prints out some data
}
#For this is to work i need to do this for example:
$file = 'c:\test.txt'
$data1 = A (Get-Content $file1)
$data1 = B ($data1)
#Same thing for data2 and then use function C:
C -data1 $data2 -data2 data2
though this works, I would like to use Piping, i must be using it wrong
Get-Content $file1 | A | B
Would give me errors obviously.
can someone help me pipe this?
Continued from my comment. For Example:
Building PowerShell Functions That Support the Pipeline
ValueFromPipeline Let's start off with a function to perform some
tests.
#region Test Function
Function Test-Object
{
[cmdletbinding()]
Param
(
[parameter(ValueFromPipeline)][int[]]$Integer
)
Process
{
$PSItem
}
}
#endregion Test Function

End a function from a sourced script without exiting script

I have a script with many other scripts sourced. Each script sourced have a function.
One of my function need to stop according to a if statement. I tried continue, break, throw, evrything I saw on internet but either my main script completely end or my function continue.
Function code:
function AutoIndus-DeployUser($path){
$yaml=Get-Content $path | ?{!$_.StartsWith("#")}
$UsersPwd=$false
$user="";$password="";$groups="";$description=""; $options=""
$yaml | %{
if (($_-match "}") -and ($UsersPwd -eq $true)){Write-Host "function should stop"; return}
*actions*
}
}
Main script:
#functions list and link to extern scripts
Get-ChildItem -Path $PSScriptRoot\functions\ | %{$script=$_.Name; . $PSScriptRoot\functions\$script}
myfunction-doesnotwork
*some code*
Edit: I saw that return should stop the function without stoping the rest of the script, unfortunatly it does not stop anything at all:
Output:
Config file found
---
Changing user _usr-dba password
Changing user _usr-dba2 password
function should stop
Changing user _usr-dba3 password
function should stop
function should stop
function should stop
function should stop
function should stop
Disabling user DisableAccounts:{
Disable-LocalUser : User DisableAccounts:{ was not found.
At C:\Scripts\AWL-MS-AUTOMATION_AND_TOOLS\functions\AutoIndus-DisableAccount.ps1:25 char:13
+ Disable-LocalUser -Name $disable
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (DisableAccounts:{:String) [Disable-LocalUser], UserNotFoundException
+ FullyQualifiedErrorId : UserNotFound,Microsoft.PowerShell.Commands.DisableLocalUserCommand
Disabling user _usr-dba
To help you understanding, my script read a file and do actions according to each line it is reading. It start acting when it encounter something like User{ and should stop when it encounter }, _usr-dba3 being out of the curvy brackets it should not be treated. This way all my other function use the same one file. (changing user password and diasabling user are two different functions/sourced scripts)
Like you can see return does not do its job, maybe I'm missing one point in the use of return but I don't get it right now.
To prematurely exit out of a function before you reach the end of it, use
return
it works like break to where it will stop execution but instead of stopping the whole thread it will return back to the line below where you called the function.
Also keep in mind if your function has an output set return will return it back, for example with the function below:
function Get-ReturnValue()
{
$returnValue = "this is my output"
return $returnValue
}
if you called it like this:
$receivedReturnValue = Get-ReturnValue
then the variable receivedReturnValue would be loaded with the output of the function.
I needed a fast solution so I changed my functions, now there is no return/continue/... but a value that turn true. It is initialized to false and the action on each yaml lines are done when the value is equal to false.
Edit: So finally the issue was I didn't used function correctly. Return only works if you return into another function. So I putted almost the entire sctipt into a function that calls the function AutoIndus-DeployUser. Now it works perfectly !

dd works but echo does not for an object passed as a parameter to a function in Laravel

I passed an object in a function in laravel.
I tried to assign the value of a property to a variable. It pops an error.
When I tried to figure out what was going on I tried to dd ()the value it worked.
But when I tried to echo the same it does not.
What am I mising.
On using this,
location1 and location2 are two objects of the location class.
The function is here:
function geodistance($location1,$location2){
dd($location1->lat);
$lat1=$location1->lat;
}
it prints
"28.612072"
But when I change the same function to
function geodistance($location1,$location2){
echo($location1->lat);
$lat1=$location1->lat;
}
The output error is:
Trying to get property 'lat' of non-object
Even the function
function geodistance($location1,$location2){
echo $location1->lat;
$lat1=$location1->lat;
}
gives the same output
The aim to remind you is to assign the value to a variable like so.
function geodistance($location1,$location2){
$lat1=$location1->lat;
}
When I echo $location1 from within the function geodistance() gives out and error which makes sense.
function geodistance($location1,$location2){
echo $location1;
$lat1=$location1->lat;
Object of class App\MyClasses\city could not be converted to string
When I dd ($location1 from the funciton like so it gives the right result.
function geodistance($location1,$location2){
dd($location1);
$lat1=$location1->lat;
like so:
city {#13410 ▼
+id: 2245
+info: "{}"
+name: "New Delhi"
+lat: "28.612072"
+lon: "77.22978"
+timezone: null
+weightedrating: null
+country_id: 1
}
It seems i am missing out something very trivial. :(
As pointed out by #salman zafar and #apokryfos, the mistake was that I was passing an array.
When I was doing a dd, after processing the first data the programme was terminated.
The array that was passed was not completely correct. The last data point in my array was not an object of the same class.
So the data ended up being corrupted when using echo. Echo would print one data after another but eventually it would get a wrong input.
The best way to catch these errors (after so much experimenting) is to write the values of the variable in a text file on each iterartion.
What that does is that it catches the error in your text file and u get to know after how many iterations the programme stopped.
Hope this helps others from making such obviously glaring mistakes which are tough to catch (atleast for me since this was the first of such errors)

How to use a function as a string while using matching pattern

I want to make use of functions to get the full path and directory name of a script.
For this I made two functions :
function _jb-get-script-path ()
{
#returns full path to current working directory
# + path to the script + name of the script file
return $PWD/${0#./*}
}
function _jb-get-script-dirname ()
{
return ${(_jb-get-script-path)##*/}
}
as $(_jb-get-script-path) should be replaced by the result of the function called.
However, I get an error: ${(_jb-get-script-path)##*/}: bad substitution
therefore i tried another way :
function _jb-get-script-path ()
{
return $PWD/${0#./*}
}
function _jb-get-script-dirname ()
{
local temp=$(_jb-get-script-path);
return ${temp##*/}
}
but in this case, the first functions causes an error : numeric argument required. I tried to run local temp=$(_jb-get-script-path $0) in case the $0 wasn't provided through function call (or i don't really know why) but it didn't change anything
I don't want to copy the content of the second fonction as i don't want to replicate code for no good reason.
If you know why those errors happen, I really would like to know why, and of course, if you have a better solution, i'd gladely hear it. But I'm really interessed in the resolution of this problem.
You need to use echo instead of return which is used for returning a numeric status:
_jb-get-script-path() {
#returns full path to current working directory
# + path to the script + name of the script file
echo "$PWD/${0#./*}"
}
_jb-get-script-dirname() {
local p="$(_jb-get-script-path)"
echo "${p##*/}"
}
_jb-get-script-dirname

Print debug messages to console from a PowerShell function that returns

Is there a way to print debug messages to the console from a PowerShell function that returns a value?
Example:
function A
{
$output = 0
# Start of awesome algorithm
WriteDebug # Magic function that prints debug messages to the console
#...
# End of awesome algorithm
return $output
}
# Script body
$result = A
Write-Output "Result=" $result
Is there a PowerShell function that fits this description?
I'm aware of Write-Output and Write-*, but in all my tests using any of those functions inside a function like the one above will not write any debug messages. I'm also aware that just calling the function without using the returned value will indeed cause the function to write debug messages.
Sure, use the Write-Debug cmdlet to do so. Note that by default you will not see debug output. In order to see the debug output, set $DebugPreference to Continue (instead of SilentlyContinue). For simple functions I will usually do something like this:
function A ([switch]$Debug) {
if ($Debug) { $DebugPreference = 'Continue' }
Write-Debug "Debug message about something"
# Generate output
"Output something from function"
}
Note that I would not recommend using the form return $output. Functions output anything that isn't captured by a variable, redirected to a file (or Out-Null) or cast to [void]. If you need to return early from a function then by all means use return.
For advanced functions you can get debug functionality a bit more easily because PowerShell provides the ubiquitous parameters for you, including -Debug:
function A {
[CmdletBinding()]
param()
End {
$pscmdlet.WriteDebug("Debug message")
"Output something from cmdlet"
}
}
FYI, it's the [CmdletBinding()] attribute on the param() statement is what makes this an advanced function.
Also don't forget about Write-Verbose and $pscmdlet.WriteVerbose() if you just want a way to output additional information that isn't debug related.

Resources