I agree with @Christian, and I add another solution.
First you can return using an array explicitly or implicitly:
explicitly
function ExplicitArray () { $myArray = @() $myArray += 12 $myArray += "Blue" return ,$myArray } Clear-Host $a = ExplicitArray Write-Host "values from ExplicitArray area[0]) and
a[1])"
implicitly
function ImplicitArray () { Write-Output 12 Write-Output "Blue" return "green" } $b = ImplicitArray Write-Host "values from ImplicitArray areb[0]),
b[1]) and
b[2])"
Second you can return a custom object:
Short form
function ReturnObject () { $value = "" | Select-Object -Property number,color $value.Number = 12 $value.color = "blue" return $value } $c = ReturnObject Write-Host "values from ReturnObject arec.number) and
c.color)"
School form
function SchoolReturnObject () { $value = New-Object PsObject -Property @{color="blue" ; number="12"} Add-Member -InputObject $value –MemberType NoteProperty –Name "Verb" –value "eat" return $value } $d = SchoolReturnObject Write-Host "values from SchoolReturnObject ared.number),
d.color) and
d.Verb)"
Third using argument by reference:
function addition ([int]
y, [ref]$R)
{
$Res =
y
$R.value = $Res
}
$O1 = 1
O3 = 0
addition
O2 ([ref]$O3)
Write-Host "values from addition
o2 is $o3"
Answer from JPBlanc on Stack OverflowI agree with @Christian, and I add another solution.
First you can return using an array explicitly or implicitly:
explicitly
function ExplicitArray () { $myArray = @() $myArray += 12 $myArray += "Blue" return ,$myArray } Clear-Host $a = ExplicitArray Write-Host "values from ExplicitArray area[0]) and
a[1])"
implicitly
function ImplicitArray () { Write-Output 12 Write-Output "Blue" return "green" } $b = ImplicitArray Write-Host "values from ImplicitArray areb[0]),
b[1]) and
b[2])"
Second you can return a custom object:
Short form
function ReturnObject () { $value = "" | Select-Object -Property number,color $value.Number = 12 $value.color = "blue" return $value } $c = ReturnObject Write-Host "values from ReturnObject arec.number) and
c.color)"
School form
function SchoolReturnObject () { $value = New-Object PsObject -Property @{color="blue" ; number="12"} Add-Member -InputObject $value –MemberType NoteProperty –Name "Verb" –value "eat" return $value } $d = SchoolReturnObject Write-Host "values from SchoolReturnObject ared.number),
d.color) and
d.Verb)"
Third using argument by reference:
function addition ([int]
y, [ref]$R)
{
$Res =
y
$R.value = $Res
}
$O1 = 1
O3 = 0
addition
O2 ([ref]$O3)
Write-Host "values from addition
o2 is $o3"
Maybe I am misunderstanding the question but isn't this just as simple as returning a list of variables, and the caller simply assigns each to a variable. That is
> function test () {return @('a','c'),'b'}
>
b = test
$a will be an array, and $b the letter 'b'
>
b
b
How to return multiple properties of an object into another function?
Struggles in understanding how to return multiple values from PowerShell script.
Passing multiple parameters to a function and returning multiple values
Return multiple Values from function
Videos
I have a PowerShell script that returns an array of 6 properties.
Here's a simplified version:
$output = @()...rest of code...$output += [PSCustomObject]@{Property1 = $someBoolProperty2 = $someValue1Property3 = $someValue2Property4 = $someValue3Property5 = $someValue4Property6 = $someValue5}
return $output | Format-Table -AutoSize
Using executePowershellCommand64BitSystem along with updateSystemInfo, how can I get all the values from the output and apply them to custom fields for the agent(s)? I've read the documentation, but it's not very straightforward. Then again, I could just be missing something.
EDIT: Maybe something like this? (can't test, need approval first):
writeFile("VSASharedFiles\Script.ps1", "C:\Scripts\Script.ps1", "All Operating Systems", "Halt on Fail")executePowershellCommand64BitSystem("C:\Scripts\Script1.ps1", " ", true, "All Operating Systems", "Halt on Fail")getVariable("Constant Value", "#global:someBool#, "someBool", "All Operating Systems", "Halt on Fail")getVariable("Constant Value", "#global:someValue1#, "someValue1", "All Operating Systems", "Halt on Fail")<similar for the remaining variables>updateSystemInfo("CustomField1", "#someBool#", "All Operating Systems", "Halt on Fail")updateSystemInfo("CustomField2", "#someValue1#", "All Operating Systems", "Halt on Fail")<similar for the remaining values>
Hi ! I have 2 function in my Script powershell. One get the value of the user and the other one use the values. I found a way to return multiple values from a function (Table).It’s working perfectly .But the values are not recognized by the second function ($Return[1] is empty). Do anyone knows the problem of my code ?
Thanks
$Button2.Add_Click({test1})
$BtnConfirm.Add_Click({test2})
Function test1($Folders,$CheckValue, $UserResearch)
{
$Folders = $TextBoxLink.Text
$CheckValue = $True
if($CheckBoxYes.Checked -eq $true)
{
$CheckValue = $True
}
elseif($CheckBoxNo.Checked -eq $true)
{
$CheckValue = $False
}
$UserResearch = $TextBoxUser.Text
Return $Folders,$CheckValue,$UserResearch
}
$Return = test1
Function test2($Return)
{
###################################### SI FILTRE ################################
if($Return[1] -eq $True)
{
New-Item -Name "superCaMarche.txt" -Path \\srv-files\RNS_Services\Informatique\Test_Depraz -Value $CheckValue
#Récupère le nom de domaine
$Domain = (Get-ADDomain).NetBIOSName
#Sotck dans une variable les objects du dossier donné par l'utilisateur
$Folders = Get-Item -Path $Path
#Parcours le dossier ou l'arborescence
ForEach ($Folder in $Folders)
{
#Récupère les droits sur un dossier et les stocks
$ACLs = Get-Acl $Folder.FullName | ForEach-Object { $_.Access }
#Parcours tous les droits sur un dossier
ForEach ($ACL in $ACLs)
{
#Controle si il existe bien des droits
If ($ACL.IdentityReference -match "\\")
{
#Controle si le dossier possède des droits lié au domaine
If ($ACL.IdentityReference.Value.Split("\")[0].ToUpper() -eq $Domain.ToUpper())
{
#Entre dans une variable le nom du groupe AD
$Name = $ACL.IdentityReference.Value.Split("\")[1]
#Vérifie que l'object récupéré est bien un groupe
If ((Get-ADObject -Filter 'SamAccountName -eq $Name').ObjectClass -eq "group")
{
#Parcours les informations du groupe récupéré
ForEach ($User in (Get-ADGroupMember $Name -Recursive | Select -ExpandProperty Name))
{ $Result = New-Object PSObject -Property @{
Path = $Folder.Fullname
Group = $Name
User = $User
FileSystemRights = $ACL.FileSystemRights
AccessControlType = $ACL.AccessControlType
Inherited = $ACL.IsInherited
}
$Result | Select group,FileSystemRights,AccessControlType,Inherited, User |Where-Object{$User.Equals($UserResearch)} |export-csv \\srv-files\RNS_Services\Informatique\Test_Depraz\"$UserResearch".csv -Append
#$Result | Select Path,Group,User,FileSystemRights,AccessControlType,Inherited
}
}
}
}
}
}
}
Either return a string that you then parse out separate values using delimiters, or return a data structure like an array.
All right, so the basics: I have a 1 button, the first button calls a function which returns an array. I have another button that needs to use the array from the first function. I've tried calling the first function from the second function and have a return statement for my array. The code for this is pretty long, but in a general sense it's just how to I return an array from one function and then use it in a second function. I've been Googleing all yesterday and haven't found anything. B…
Hello,
I'm working with classes right now and try to implement classes in my functions. I have a simple class which takes path and return object with name,date,workstation etc. I don't know much about PS classes so my question is:
Should class only return one object at time or could I implement foreach statement and return multiple object within a class? So if I run [MyClass]::new($path) should it return just one object or could I irritate through $path variable and return multiple objects? What is the best practice?
It this sounds stupid, I get that but no dev background so need to learn from my mistakes :)
Thanks :)
In your powershell script you can build an Hashtable based on your necessity:
[hashtable]$Return = @{}
$Return.ReturnCode = [int]1
$Return.ReturnString = [string]"All Done!"
Return $Return
In C# code handle the Psobject in this way
ReturnInfo ri = new ReturnInfo();
foreach (PSObject p in psObjects)
{
Hashtable ht = p.ImmediateBaseObject as Hashtable;
ri.ReturnCode = (int)ht["ReturnCode"];
ri.ReturnText = (string)ht["ReturnString"];
}
//Do what you want with ri object.
If you want to use a PsCustomobject as in Keith Hill comment in powershell v2.0:
powershell script:
$return = new-object psobject -property @{ReturnCode=1;ReturnString="all done"}
$return
c# code:
ReturnInfo ri = new ReturnInfo();
foreach (PSObject p in psObjects)
{
ri.ReturnCode = (int)p.Properties["ReturnCode"].Value;
ri.ReturnText = (string)p.Properties["ReturnString"].Value;
}
CB.'s answer worked great for me with a minor change. I did not see this posted anywhere (in regards to C# and PowerShell) so I wanted to post it.
In my PowerShell script I created created a Hashtable, stored 2 values in it (a Boolean and an Int) and then converted that into a PSObject:
$Obj = @{}
if($RoundedResults -ilt $Threshold)
{
$Obj.bool = $true
$Obj.value = $RoundedResults
}
else
{
$Obj.bool = $false
$Obj.value = $RoundedResults
}
$ResultObj = (New-Object PSObject -Property $Obj)
return $ResultObj
And then in my C# code I did the same thing that CB. did but I had to use Convert.ToString in order to successfully get the values back:
ReturnInfo ri = new ReturnInfo();
foreach (PSObject p in psObjects)
{
ri.ReturnCode = Convert.ToBoolean(p.Properties["ReturnCode"].Value;)
ri.ReturnText = Convert.ToString(p.Properties["ReturnString"].Value;)
}
I found the answer to this via the following StackOverflow post: https://stackoverflow.com/a/5577500
Where Kieren Johnstone says:
Use Convert.ToDouble(value) rather than (double)value. It takes an object and supports all of the types you asked for! :)