r/PowerShell • • Oct 16 '26

Question REPOST Issue with $PROFILE function

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 the piped command: tee, (alias of Tee-Object) 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.

2 Upvotes

8 comments sorted by

View all comments

-4

u/tommyfly Oct 20 '26

This is from Gemini AI, so no guarantees, but I was not sure what the issue could be.

The Root Cause: PowerShell Scoping The reason $b is empty after calling gethash comes down to PowerShell variable scoping. When you run a function, PowerShell creates a temporary local scope for it. Inside your function, tee -Variable b (or Tee-Object -Variable b) creates and updates the variable $b only within that function's local scope. Once the function finishes executing, its local scope is destroyed, and $b disappears with it. When you ran the exact same command directly in your terminal, you were executing it in the global/session scope, which is why $b persisted there. Solutions Depending on how you want to use the hash, here are the best ways to fix or improve your function: Option 1: Save it to the Global Scope (If you want $b available everywhere) If you specifically want $b to be stored globally whenever you run the function, you can target the global scope explicitly:

function gethash { param([string]$string = "")

if ([string]::IsNullOrWhiteSpace($string)) {
    Write-Output "input not valid"
    return
}

# Assign and output using the global scope
$global:b = (Get-FileHash -Algorithm sha256 $string).Hash
$global:b

}

Option 2: Let standard pipeline assignment handle it (Recommended) Instead of forcing a global variable inside the function, it is usually cleaner to let the function return the value normally. This allows you to assign it to any variable name you want directly from the prompt:

function gethash { param([string]$string = "")

if ([string]::IsNullOrWhiteSpace($string)) {
    Write-Output "input not valid"
    return
}

(Get-FileHash -Algorithm sha256 $string).Hash

}

How to use it:

$b = gethash "path\to\file.txt"