testing for stuff

170 views
Skip to first unread message

Ian Kelly

unread,
Jul 27, 2022, 12:53:02 PM7/27/22
to GAM for Google Workspace
Hi, I'm trying to use GAM to get output so I can check things.
For example, check if a user exists before I go ahead and run the create user command. 
I know it passes back an error, however, in my script I can handle it by not attempting to create a new user if I check if it exists. 

so, in powershell $check = gam whatis us...@mydomain.com

nothing gets passed back in to the variable. is there a mechanism for this you know?

Many thanks

Ross Scroggs

unread,
Jul 27, 2022, 2:29:18 PM7/27/22
to google-ap...@googlegroups.com
Ian,

This works for me:

User does not exist:

PS C:\Users\Administrator> $cmdOutput = gam whatis non...@domain.com

Email Address: non...@domain.com, Does not exist

PS C:\Users\Administrator> echo $cmdOutput

PS C:\Users\Administrator>


User exists:

PS C:\Users\Administrator> $cmdOutput = gam whatis us...@domain.com

PS C:\Users\Administrator> echo $cmdOutput

User: us...@domain.com

  Settings:

...


Ross



--
You received this message because you are subscribed to the Google Groups "GAM for Google Workspace" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-apps-man...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-apps-manager/ccfb3034-bc67-476b-95d0-0fbd7bb2125cn%40googlegroups.com.


--

Maj Marshall Giguere

unread,
Jul 27, 2022, 2:48:12 PM7/27/22
to google-ap...@googlegroups.com
I am far from being a PowerShell expert, bash is my thing.

PWRSH will set $? to true if a command is successful, otherwise false.  
if ( !$? ) {
   # something bad happened
}

Truthiness with return codes can be a slippery little critter in any shell, so you could check the builtin PWRSH var $LASTEXITCODE to see what the command returned as an exit code.  GAM seems to return exit code 59 for a failure of "whatis" and 20 for success.  Your mileage may vary.

Maj Marshall E Giguere

NH Wing Director of IT

Civil Air Patrol, U.S. Air Force Auxiliary

GoCivilAirPatrol.com

nhwg.cap.gov

Volunteers serving America's communities, saving lives, and shaping futures.



--

Chris River

unread,
Jul 27, 2022, 3:07:45 PM7/27/22
to GAM for Google Workspace
You could just check for null; for example, if (-not $check) { gam create user ... } else { whatever you want to do with found user }

If you do want to capture the error message in the variable, you can redirect the stderr stream to the stdout stream by appending "2>&1" at the end, like this: $check = gam whatis us...@mydomain.com 2>&1

It might be more efficient to just run "gam create user ..." instead of checking first; the command will fail for email addresses that are already in use. Or, print all users first, then do a lookup and only create those that don't exist. For example: $test = gam print users; if (-not $test.contains('us...@mydomain.com')) { gam create user ... }

Mikhail Sutormin

unread,
Jul 28, 2022, 12:23:26 AM7/28/22
to GAM for Google Workspace
This is how I do it.

if (([string] (& $gam info user $user noaliases nolicenses 2>&1)) -match 'Does not exist') {
    write-host 'New user' $user 'does not exist in Gmail yet.'
    }

Code 
$gam info user $user noaliases nolicenses 

returns the following
User: us...@domain.com, Does not exist

so you just check for "Does not exist" string in the output.


In other cases, sometimes you can use formatjson switch to get output in JSON which can easily be converter to a standard PS object

Outputs that look like a .csv can also be converted to PS object on the fly, for example:

$csv = & $gam user $user print drivefileacls DOCUMENT_ID | ConvertFrom-Csv

Ian Kelly

unread,
Jul 28, 2022, 5:56:29 AM7/28/22
to GAM for Google Workspace
Thank you all, some really interesting solutions here. 

@Marsh because the command returns something in either case, I think it will always evaluate to true (correct me if I'm wrong)

I'm new to my organisation, so I'm refactoring the new user process, which is very delicate in various ways, so if I run the script and the user has worked for us before as a contractor, they may still have an account, so I want it to catch this and tell me gracefully, rather than just giving me an error at the end. also I could potentially change group memberships in a later iteration of the script.  It's morphing into an procedural program, but ultimately, I'd like to make it OO, but I am new to it. 

@Mikhail

I've played with your solution, you have $gam meaning you're using a variable for the command? also when I substitute it for the command and add a non existent email, I get this error, so it doesn't say does not exist. FYI

 gam : 

At line:1 char:1

+ gam info user nota...@mydomain.com

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : NotSpecified: (:String) [], RemoteException

    + FullyQualifiedErrorId : NativeCommandError

 

ERROR: 404: Resource Not Found: userKey - userNotFound 

Ross Scroggs

unread,
Jul 28, 2022, 11:01:28 AM7/28/22
to google-ap...@googlegroups.com
Ian,

In Advanced GAM, the whatis command sets the return code:

ENTITY_IS_A_USER_RC = 20

ENTITY_IS_A_USER_ALIAS_RC = 21

ENTITY_IS_A_GROUP_RC = 22

ENTITY_IS_A_GROUP_ALIAS_RC = 23

ENTITY_IS_AN_UNMANAGED_ACCOUNT_RC = 24

ENTITY_IS_UKNOWN_RC = 59


Ross


--
You received this message because you are subscribed to the Google Groups "GAM for Google Workspace" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-apps-man...@googlegroups.com.


--

Maj Marshall Giguere

unread,
Jul 28, 2022, 12:31:09 PM7/28/22
to google-ap...@googlegroups.com
Ian

When I tested using an non-existent account PWRSH returned "False"

Maj Marshall E Giguere

NH Wing Director of IT

Civil Air Patrol, U.S. Air Force Auxiliary

GoCivilAirPatrol.com

nhwg.cap.gov

Volunteers serving America's communities, saving lives, and shaping futures.


--

Maj Marshall Giguere

unread,
Jul 28, 2022, 12:58:10 PM7/28/22
to google-ap...@googlegroups.com
Ian;

Interestingly I did not test what happens with a successful query and since GAM always returns some value other than "0" pwrsh reports "False" even on success.  The $LASTEXITCODE value returned for success/exists is 20.  My bad, I should have checked both cases.

Something to keep in mind with shells and exit codes, and this goes all the way back to Ritchie & Kernighan in the 1970's UNIX implementation.  Any exit code "0" (zero) is considered  success and other exit code is considered (false) and pwrsh appears to be no exception.  Yes, this is the complete opposite of how we normally think about true vs false in programming languages, i.e. zero == false, anything else == true.

Maj Marshall E Giguere

NH Wing Director of IT

Civil Air Patrol, U.S. Air Force Auxiliary

GoCivilAirPatrol.com

nhwg.cap.gov

Volunteers serving America's communities, saving lives, and shaping futures.


Ian Kelly

unread,
Jul 28, 2022, 5:27:19 PM7/28/22
to GAM for Google Workspace
Ha, great thank you Marsh, et al :) 

I found that searching for a user that doesn't exist throws and error, and this is possibly a bit of a hammer to crack a nut, as the exception seems to be a bit generic, however. I used a try catch to catch the powershell error

```function New-GoogleUser {
  [CmdletBinding()]
  param (
    [Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()][string]$fullname,
    [Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()][string]$firstname,
    [Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()][string]$lastname,
    [Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()][string]$password,
    [Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()][string]$email
  )
  $result = $null
  try {
    gam info user $email
  }
  catch[System.Management.Automation.RemoteException]{
      write-host "the user may already exist in google..."
      $result = $false
      return $result
  }
  finally{
    $Error.Clear()
  }
  gam create user ($fullname.Split(" ") -join ".") firstname $firstname lastname $lastname password $password.Password
}```

Mikhail Sutormin

unread,
Jul 28, 2022, 6:54:31 PM7/28/22
to GAM for Google Workspace
Hi Ian,

Yes, I usually declare gam as a variable so I could easily reuse the same code on my service machines without needing to add gam to system variables.

I also think we are using different flavours of gam, hence the difference in output. I use Ross's GAM. So:

$gam = 'C:\GAMADV-XTD3\gam.exe'
& $gam info user US...@DOMAIN.COM 2>&1

returns

User: US...@DOMAIN.COM, Does not exist

For classic GAM you could try the following check:

& $gam info user US...@DOMAIN.COM  2>&1)) -match 'Error: 404'


Another alternative mentioned above is to fetch all users first and check locally

$users = & $gam print users | convertfrom-csv
$users.primaryEmail -icontains "US...@DOMAIN.COM"

That returns True is user exists and False if it doesn't. Makes it faster if you create a big chunk of users.

Ross Scroggs

unread,
Jul 28, 2022, 7:04:07 PM7/28/22
to google-ap...@googlegroups.com
Ian,

As you're using  Advanced GAM, the whatis command sets the return code:

ENTITY_IS_A_USER_RC = 20

ENTITY_IS_A_USER_ALIAS_RC = 21

ENTITY_IS_A_GROUP_RC = 22

ENTITY_IS_A_GROUP_ALIAS_RC = 23

ENTITY_IS_AN_UNMANAGED_ACCOUNT_RC = 24

ENTITY_IS_UKNOWN_RC = 59


If you get a 59, the email address is not used.


Ross


Ross


--
You received this message because you are subscribed to the Google Groups "GAM for Google Workspace" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-apps-man...@googlegroups.com.


--

Ian Kelly

unread,
Aug 1, 2022, 6:04:12 AM8/1/22
to GAM for Google Workspace
Thanks for your help, so using the $LASTEXITCODE is very useful. 
Reply all
Reply to author
Forward
0 new messages