vmware / PowerCLI-Example-Scripts

http://blogs.vmware.com/powercli
Other
757 stars 603 forks source link

run script second time failed #530

Closed yanlu2 closed 2 years ago

yanlu2 commented 2 years ago

Describe the bug

@bwuch

my script is running good on first run and got error message on second run when I changed the vcenter name. the error is

run first goodC:\Users\luy13> C:\PS_scripts\vCenter\vCenter-Export-User-Role2.ps1

Export users/roles in Organization in Pontus rsaengbdvc4.rsa.lab.emc.com

Name Port User

server.com 443 VSPHERE.LOCAL\Administrator

Name : server.com ServiceUri : https://server.com/sso-adminserver/sdk/vsphere.local User : administrator@vsphere.local Id : /SsoAdminServer=vsphere.local/administrator@rsaengbdvc4.rsa.lab.emc.com IsConnected : True Client : VMware.vSphere.SsoAdminClient.SsoAdminClient RefCount : 1

FormatError : The term 'FormatError' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At C:\PS_scripts\vCenter\Group.ps1:218 char:26

    Write-Error (FormatError $_.Exception)
                 ~~~~~~~~~~~

CategoryInfo : ObjectNotFound: (FormatError:String) [], CommandNotFoundException FullyQualifiedErrorId : CommandNotFoundException

Here is vCenter-Export-User-Role2.ps1

. "C:\PS_scripts\vCenter\Group.ps1" $path="C:\Temp\Reports\vCenters\" # output report file location $server="server1.com" # VCD server $hostname=$server.Split(".")[0]

$orglistfile=$path+"orglist.txt"

$username = "administrator@vsphere.local" $passwd = "Fr33fri3s!" $localdomain="vsphere.local" $corpdomain="corp" Write-host "`nExport users/roles in $myOrg Organization in Pontus $server" $csvfile=$path+$hostname+"-grpmbr.csv"

Connect-VIServer -Server $server -user $username -password $passwd

list all users in org

Connect-SsoAdminServer -Server $server -User $username -Password $passwd

$vcgroups=Get-SsoGroup -Domain $localdomain For ($j = 0; $j -le ($vcgroups.length - 1); $j += 1) { $vcgroupname=$vcgroups[$j].name

$vcgroups[$j].Domain

#Get-SsoGroup -Name administrators -Domain vsphere.local
#Write-Output "group",$j, $vcgroupname
$users=Get-SsoGroup -Name $vcgroupname -Domain $localdomain | Get-SsoPersonUser

$users |Export-Csv -Path $csvfile -NoTypeInformation

for ($i = 0; $i -le ($users.length - 1); $i += 1) {
    $username=$users[$i].name
    $useremail=$users[$i].emailaddress
    write-host $i, $vcgroupname, $username, $useremail
    "$i, $vcgroupname, $username, $useremail"  | Out-File -FilePath $csvfile -Append
}

}

Here is group.ps1 I get from https://www.powershellgallery.com/packages/VMware.vSphere.SsoAdmin/1.3.4/Content/Group.ps1

Reproduction steps

1.run first time good
2.run second time got error after change vCenter name
3.
...

Expected behavior

the script pull members from all groups in a vcenter and should be same after i changed vcenter name to another. I have to close PS ISE to do second run.

Additional context

No response

yanlu2 commented 2 years ago

here is output PS C:\Users\luy13> $env:PSModulePath C:\Users\luy13\Documents\WindowsPowerShell\Modules;C:\Program Files\WindowsPowerShell\Modules;C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\;C:\Program Files (x86)\WindowsPowerShell\Modules\

How can I add this module to it? sorry I'm new to PowerShell and PowerCLI

bwuch commented 2 years ago

Hi @yanlu2 - I didn't realize that this module was available on the PowerShell gallery, so you may already have it installed. You could confirm this with syntax like Get-Module -ListAvailable VMware.vSphere.SsoAdmin. Looking at the sample code, I see a Connect-SsoAdminServer but do not see reference to Disconnect-SsoAdminServer. If this script is only working on the first instance of vCenter Server, you may want to try calling the disconnect function at the end of your loop before re-running the Connect-SsoAdminServer function a second time to ensure you are only connected to one server for each iteration.

yanlu2 commented 2 years ago

here is output, PS C:\Users\luy13> Get-Module -ListAvailable VMware.vSphere.SsoAdmin

Directory: C:\Program Files\WindowsPowerShell\Modules

ModuleType Version Name ExportedCommands


Script 1.3.7 VMware.vSphere.SsoAdmin {Connect-SsoAdminServer, Disconnect-SsoAdminServer, New-SsoPersonUser, Get-SsoPersonUser...}

and I added disconnect command but got same issue. Disconnect-SsoAdminServer -Server $server

PS C:\Users\luy13> C:\PS_scripts\vCenter\vCenter-Export-User-Role2.ps1

Export users/roles in Organization in Pontus server.com

Name : server1.com ServiceUri : https://server1.com:7444/sso-adminserver/sdk/vsphere.local User : administrator@vsphere.local Id : /SsoAdminServer=vsphere.local/administrator@server.com IsConnected : True Client : VMware.vSphere.SsoAdminClient.SsoAdminClient RefCount : 1

FormatError : The term 'FormatError' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At C:\PS_scripts\vCenter\Group.ps1:218 char:26

bwuch commented 2 years ago

Interesting, the module is installed, so I would have assumed that would work. It might be that the FormatError function is not included in the FunctionsToExport list. For grins, would you be able to add the following near the top of your script, so that it is executed before the other functions?

function FormatError {
    param(
        [System.Exception]
        $exception
    )
    if ($exception -ne $null) {
        if ($exception.InnerException -ne $null) {
            $exception = $exception.InnerException
        }

        # result
        $exception.Message
    }

}

This is the function you are being told is not recognized as the name of a cmdlet, function, script file, or operable program, so by placing it in your script directly we'll know that it is the name of a function. Perhaps this will help us see the specific error you are hitting.

yanlu2 commented 2 years ago

I have put FormatError fuction on top of my script and got another error. PS C:\Users\luy13> C:\PS_scripts\vCenter\vCenter-Export-User-Role2.ps1

Export users in groups in vCenter server.com

Name : server.com ServiceUri : https://server.com/sso-adminserver/sdk/vsphere.local User : administrator@vsphere.local Id : /SsoAdminServer=vsphere.local/administrator@server.com IsConnected : True Client : VMware.vSphere.SsoAdminClient.SsoAdminClient RefCount : 1

Get-SsoGroup : The term 'RemoveWildcardSymbols' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At C:\PS_scripts\vCenter\vCenter-Export-User-Role2.ps1:47 char:11

bwuch commented 2 years ago

Similar to FormatError before, RemoveWildcardSymbols is another internal function from the module that is not exported through FunctionsToExport. Since adding the function into your script got us a bit further, you could try the same thing again... but instead of just adding FormatError to your script add all of the internal helper functions from the module, included below.

# Internal helper functions
function HasWildcardSymbols {
    param(
        [string]
        $stringToVerify
    )
    (-not [string]::IsNullOrEmpty($stringToVerify) -and `
        ($stringToVerify -match '\*' -or `
                $stringToVerify -match '\?'))
}

function RemoveWildcardSymbols {
    param(
        [string]
        $stringToProcess
    )
    if (-not [string]::IsNullOrEmpty($stringToProcess)) {
        $stringToProcess.Replace('*', '').Replace('?', '')
    }
    else {
        [string]::Empty
    }
}

function FormatError {
    param(
        [System.Exception]
        $exception
    )
    if ($exception -ne $null) {
        if ($exception.InnerException -ne $null) {
            $exception = $exception.InnerException
        }

        # result
        $exception.Message
    }

}
yanlu2 commented 2 years ago

acturally, I excluded. "C:\PS_scripts\vCenter\Group.ps1" from my script, there is no FormatError and other errors.