r/PowerShell • • Oct 16 '26

Question Function Issue in $PROFILE path

Hello everyone. I hope you are having a good time.


function gethash {

param([string]$string = "")

if ($string -eq [string]::Empty -or $string -isnot [string])

{

Write-Output "input not valid"

}

else

{

(Get-FileHash -algorithm sha256 $string).Hash | tee -Variable b

}

}  

I Have this function in my $Profile script. when i run gethash something it returns the hash string as expected, but when I try to print the variable containing the hash i just obtained from piped command tee, (alias of Tee-Object) as an input with `$b

it prints nothing, the variable is not saved.

on the other hand, if i copy the exact same command from the $profile function directly through the terminal, $b prints what expected: the hash of the file.

I haven't used this function so much, but I'm pretty sure it worked before today.

Thanks in advance to any who will respond.

1 Upvotes

7 comments sorted by

View all comments

1

u/jimb2 Oct 18 '26 edited Oct 18 '26

If you want a result saved as a variable in the main scope (outside of the function) specify the global scope.

This is very handy for working functions that you use from the command line.

For example, I have an AD user lookup function ADU that I typically use multiple times a day in my identity management job. It lists all users matched by an "anr and" ldap lookup, displays the result on the screen, and saves the list of users and some of the useful properties to a variable $adu for reuse. (There's actually a bunch of these lookup functions that save the result with the variable having the same name as the function.)

adu john smith

finds all users with names matching john* and smith*

This function (set) is dot run from the startup profile like

.  c:\ps\startup\ADUtils.ps1

(These funtions could alternately go in a module. Maybe one day. These are not funtions that I would incoprorate in other code, they are designed as a command line tools only.)

At the end of the function, I save the array result globally:

$global:adu = $userArray

So the result is available if I want to review it or pipe it into something else.

I think this might be similar to what you are trying to achieve.