Varible found in expression is not defined?

Looking for help translating this error:

Variable: 'newuser' found in expression: $newuser is not defined.

Script:

$newuser = read-host "Enter new username"

$adminuser = get-pswho | select-object -expandproperty User

$s = new=pssession -computername "host" -credential domain\user

invoke-command -session $s -scriptblock {if (@(get-aduser -filter { SamAccountName -eq $newuser }).Count -eq 0) { write-warning -message "User $newuser does not exist."}}

I should add, I am entering a value for $newuser when prompted.

Thanks!

 

If you define a variable outside a script block it’s by default invisible inside the script block. :wink:

But - lucky you - you’re not first one with this challenge:

https://powershell.org/forums/topic/invoke-command-scriptblock-variables/

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_script_blocks?view=powershell-6

Ooo very cool. I like the thought of the $Using: scope method. Trying it myself as such:

$s = new-pssession -computername "hostname" -credential domain\user

$newuser = read-host "Enter new username."

invoke-command -session $s -scriptblock {if (@(get-aduser -filter {SameAccountName -eq $Using:newuser }).Count -rq 0) {

      Write-Warning -message "User $Using:newuser does not exist." }}

Returns the error:

Variable: 'Using' found in expression: $Using is not defined.

And I’m using PS 5.1 on both my Win10 client and the server the remote pssession is on. I think I’d prefer this one since it’s simpler and more elegant but I’ll give the arglist way a shot too.

Try it like this:

$s = new-pssession -computername ‘hostname’ -credential domain\user
$newuser = read-host “Enter new username.”
Invoke-Command -session $s -ScriptBlock {
If(-not(Get-ADUser -Filter “sAMAccountName -eq ‘$USING:newuser’”)){
Write-Warning -message “User $Using:newuser does not exist.”
}
}

Because “sAMAccountName” has to be unique in a domain you don’t have to use the count thing in the query.