Link to home
Start Free TrialLog in
Avatar of abcd ab01
abcd ab01Flag for United States of America

asked on

powershell script- need help-

I'm trying to run the script.

It must check the OU and search the Users and look for IDs and save to c:\temp\envoy2 folder.

Not getting error but don't see folder has anything. Please help me soon.
# envoy-ad-sync.ps1
# for more information, visit https://help.envoy.com/active-directory-integration/PROCESS #This is where the script executes
{
  #############################################################################
  ### Customize the following variables
  #############################################################################

  # List of Organizational Units (OUs)
  # The script will search each OU and add all
  # matches to your employee directory
  #$OUS =  @(
   # "OU=rti,OU=Depts,OU=Dept 58,OU=Users,DC=DC02,DC=contoso,DC=com"
  # )

  # Envoy Plugin Token
  # - This is already pre-populated with your plugin token.
  # - Available from the first step of the plugin configure process in Envoy.
  $INSTALL_TOKEN="4efcab52-1103-427a-8ac7-2641b965f585"

  # Path to store CSV file (edits optional)
  # Customize the path where envoy stores temp files
  # while syncing
  $ENVOYEXPORTPATH="C:\temp\Envoy2"
  $ENVOYEXPORT= $ENVOYEXPORTPATH + "\envoy_export.csv"

  #############################################################################
  ###  Do not modify the script below
  #############################################################################

  Write-Output "Running Envoy AD Sync"

  # Ensure path to CSVs exists
  $pathexist = Test-Path -Path $ENVOYEXPORTPATH
  If ($pathexist -eq $false) {
    Write-Output "Creating directory to store sync CSVs"
    New-Item -type directory -Path $ENVOYEXPORTPATH
  }

  # Clean up previous Envoy exports first
  if (Test-Path -Path $ENVOYEXPORT) {
    Write-Output "Cleaning up previous CSV"
    Remove-Item $ENVOYEXPORT
  }

  Import-Module ActiveDirectory
  # The format of the CSV should be the following:
  # Full Name, employee@company.com, 555-555-5555, assistant@company.com

  $out = @()
  foreach($ou in $OUS) {
    Write-Output "Exporting $ou to CSV"
    $out += Get-ADUser -searchbase $ou -Properties * -Filter * |
    Select-Object @{Label = "Display Name";Expression = {$_.DisplayName}},
    @{Label = "Email";Expression = {$_.Mail}},
    @{Label = "Phone";Expression = {$_.telephoneNumber}}
  }

  #Export CSV report
  $out | Export-Csv -Path $ENVOYEXPORT -NoTypeInformation

  Write-Output "Syncing CSV with Envoy"
  $url = "https://app.envoy.com/platform/ad/sync-ad-contacts?install_token=$INSTALL_TOKEN"
  $fileContent = Get-Content $ENVOYEXPORT | Out-String
  $fileContentBytes = [System.Text.Encoding]::UTF8.GetBytes($fileContent)
  $fileContentEncoded = [System.Convert]::ToBase64String($fileContentBytes)
  Try {
    Invoke-RestMethod -Uri $url -Method Post -Body  @{ "data" = $fileContentEncoded; } -ContentType "multipart/form-data" -TimeoutSec 30
    Write-Output "Completed"
  }
  Catch {
    $ErrorMessage = $_.Exception.Message
    $FailedItem = $_.Exception.GetType().FullName
    Write-Output "Failed: $FailedItem - $ErrorMessage"
    echo "i am here"
  }
}

Open in new window

Avatar of Qlemo
Qlemo
Flag of Germany image

Do you see the progress messages written to the PS console?
Avatar of abcd ab01

ASKER

what do you meant by?
I'm confused by the following , may be I'm wrong
"OU=rti,OU=Depts,OU=Dept 58,OU=Users,DC=DC02,DC=contoso,DC=com"
our users folder is under> domain controller> dc02, domain name> contoso.com, OU-rti\Depts\users

please help me
Then "OU=Users,OU=Depts,OU=OU-rti,DC=DC02,DC=contoso,DC=com" should be correct. You need to go in reverse order if looking at the folder tree.
The script writes out some text messages to show progress - all lines with Write-Output. You should at least see some of them, depending on the correctness of OU etc.
is this correct?
OU=OU-rt
can we do remote session if possible?
I dont see its creating any list in the c:\temp\envoy2?
what to check?
this scrip is basically for envoy to sysnc up with AD
Avatar of oBdA
oBdA

Well, maybe stating the way-too-obvious here, but for starters, the complete "$OUs" array with the OU names is still commented, so "foreach($ou in $OUS) {" will happily do exactly nothing.

Then to make sure you have the correct OU path, try it like this:
- Open the ADUC console, go to the OU that you want to sync, pick any user inside that OU, and open its properties.
- Go to the Account tab, make note of the "pre-Windows 2000" user logon name.
- Open a Powershell console, enter
Import-Module ActiveDirectory
Get-ADUser -Identity InsertTheUserNameFromAboveHere | Select Dist*
- From the DistinguishedName returned, discard everything until (but not including) the first "OU=" - this is the OU path you need.
When I'm done with this thread, is there any way to delete the code?
Please remove domain name and ou names
Great!! That's ok thanks a lot!!!
One more request- please change wherever you see- dco2, rti and envoy2
Thank u!
Hi Obda,

I followed your above instructions.
Result came out as> PS H:\> Import-Module ActiveDirectory
PS H:\> Get-ADUser -Identity username | Select Dist*

DistinguishedName
-----------------
CN=firstname lastname,OU=Users,OU=test - Doc 01,OU=Dept,OU=Market,DC=r...


Note: is this the correct OU path to be entered into the script? what to cxclude? under dc: Idont see domain, it is just with r and 3 dots. What does it mean. I'm missing dc=domaincontroller and dc=com too. Please advise me.

"maybe stating the way-too-obvious here, but for starters, the complete "$OUs" array with the OU names is still commented, so "foreach($ou in $OUS) {" will happily do exactly nothing."

what would be the exact syantex? I'm not a power shell coder. Please write me in detail.

Do I need to create a temp\envoy folder in c or will be created by itself?
This should give you the full path for the user, with anything until the first "OU=" to be discarded:
Get-ADUser -Identity username | Select -Expa Dist*

Open in new window

This is bit more complicated, but gives the you the path just as it needs to be used:
"OU=" + ((Get-ADUser -Identity username).distinguishedName -split ',OU=', 2)[1]

Open in new window


Put the result in line 13 in the script below.
One more error: In the script you posted, you removed a line break before the PROCESS (line 2), so the commented "$OUs" array and the OU search root aside, all the script ever did was to create a scriptblock, without actually executing anything of it.

If this still doesn't work with the correct OU path in it, post the original, unchanged, envoy-ad-sync.ps1.
# envoy-ad-sync.ps1
# for more information, visit https://help.envoy.com/active-directory-integration/
PROCESS #This is where the script executes
{
	#############################################################################
	### Customize the following variables
	#############################################################################

	# List of Organizational Units (OUs)
	# The script will search each OU and add all
	# matches to your employee directory
	$OUS = @(
		"OU=rti,OU=Depts,OU=Dept 58,OU=Users,DC=DC02,DC=contoso,DC=com"
	)

	# Envoy Plugin Token
	# - This is already pre-populated with your plugin token.
	# - Available from the first step of the plugin configure process in Envoy.
	$INSTALL_TOKEN = "4efcab52-1103-427a-8ac7-2641b965f585"

	# Path to store CSV file (edits optional)
	# Customize the path where envoy stores temp files
	# while syncing
	$ENVOYEXPORTPATH = "C:\temp\Envoy2"
	$ENVOYEXPORT = $ENVOYEXPORTPATH + "\envoy_export.csv"

	#############################################################################
	###  Do not modify the script below
	#############################################################################

	Write-Output "Running Envoy AD Sync"

	# Ensure path to CSVs exists
	$pathexist = Test-Path -Path $ENVOYEXPORTPATH
	If ($pathexist -eq $false) {
		Write-Output "Creating directory to store sync CSVs"
		New-Item -type directory -Path $ENVOYEXPORTPATH
	}

	# Clean up previous Envoy exports first
	if (Test-Path -Path $ENVOYEXPORT) {
		Write-Output "Cleaning up previous CSV"
		Remove-Item $ENVOYEXPORT
	}

	Import-Module ActiveDirectory
	# The format of the CSV should be the following:
	# Full Name, employee@company.com, 555-555-5555, assistant@company.com

	$out = @()
	foreach($ou in $OUS) {
		Write-Output "Exporting $ou to CSV"
		$out += Get-ADUser -searchbase $ou -Properties * -Filter * |
		Select-Object @{Label = "Display Name";Expression = {$_.DisplayName}},
		@{Label = "Email";Expression = {$_.Mail}},
		@{Label = "Phone";Expression = {$_.telephoneNumber}}
	}

	#Export CSV report
	$out | Export-Csv -Path $ENVOYEXPORT -NoTypeInformation

	Write-Output "Syncing CSV with Envoy"
	$url = "https://app.envoy.com/platform/ad/sync-ad-contacts?install_token=$INSTALL_TOKEN"
	$fileContent = Get-Content $ENVOYEXPORT | Out-String
	$fileContentBytes = [System.Text.Encoding]::UTF8.GetBytes($fileContent)
	$fileContentEncoded = [System.Convert]::ToBase64String($fileContentBytes)
	Try {
		Invoke-RestMethod -Uri $url -Method Post -Body  @{ "data" = $fileContentEncoded; } -ContentType "multipart/form-data" -TimeoutSec 30
		Write-Output "Completed"
	} Catch {
		$ErrorMessage = $_.Exception.Message
		$FailedItem = $_.Exception.GetType().FullName
		Write-Output "Failed: $FailedItem - $ErrorMessage"
		echo "i am here"
	}
}

Open in new window


Do I need to create a temp\envoy folder in c or will be created by itself?
Have a close look at lines 33-38 above.
I followed your instructions and ended with the following error-

PS C:\Windows\system32> # envoy-ad-sync.ps1
PS C:\Windows\system32> # for more information, visit https://help.envoy.com/act
ive-directory-integration/
PS C:\Windows\system32> PROCESS #This is where the script executes
Missing statement block after process ( condition ).
At line:1 char:8
+ PROCESS <<<<  #This is where the script executes
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordEx
   ception
    + FullyQualifiedErrorId : MissingStatementBlock
Don't paste the script into a PS console. Save it as envoy-ad-sync.ps1 or Whatever.ps1 to test it.
I ran the way you said above- following error attached below- please let me know where to edit the script? it should be creating a .csv file but don't see yet? Thanks for your help.

....

# envoy-ad-sync.ps1
# for more information, visit https://help.envoy.com/active-directory-integration/
PROCESS #This is where the script executes
{
      #############################################################################
      ### Customize the following variables
      #############################################################################

      # List of Organizational Units (OUs)
      # The script will search each OU and add all
      # matches to your employee directory
      $OUS = @(
            "OU=Users,OU=first - second 01,OU=name,OU=constco,DC=microsoft,DC=com"
      )

      # Envoy Plugin Token
      # - This is already pre-populated with your plugin token.
      # - Available from the first step of the plugin configure process in Envoy.
      $INSTALL_TOKEN = "4efcab52-1103-427a-8ac7-2641b965f585"

      # Path to store CSV file (edits optional)
      # Customize the path where envoy stores temp files
      # while syncing
      $ENVOYEXPORTPATH = "C:\temp\Envoy"
      $ENVOYEXPORT = $ENVOYEXPORTPATH + "\envoy_export.csv"

      #############################################################################
      ###  Do not modify the script below
      #############################################################################

      Write-Output "Running Envoy AD Sync"

      # Ensure path to CSVs exists
      $pathexist = Test-Path -Path $ENVOYEXPORTPATH
      If ($pathexist -eq $false) {
            Write-Output "Creating directory to store sync CSVs"
            New-Item -type directory -Path $ENVOYEXPORTPATH
      }

      # Clean up previous Envoy exports first
      if (Test-Path -Path $ENVOYEXPORT) {
            Write-Output "Cleaning up previous CSV"
            Remove-Item $ENVOYEXPORT
      }

      Import-Module ActiveDirectory
      # The format of the CSV should be the following:
      # Full Name, employee@company.com, 555-555-5555, assistant@company.com

      $out = @()
      foreach($ou in $OUS) {
            Write-Output "Exporting $ou to CSV"
            $out += Get-ADUser -searchbase $ou -Properties * -Filter * |
            Select-Object @{Label = "Display Name";Expression = {$_.DisplayName}},
            @{Label = "Email";Expression = {$_.Mail}},
            @{Label = "Phone";Expression = {$_.telephoneNumber}}
      }

      #Export CSV report
      $out | Export-Csv -Path $ENVOYEXPORT -NoTypeInformation

      Write-Output "Syncing CSV with Envoy"
      $url = "https://app.envoy.com/platform/ad/sync-ad-contacts?install_token=$INSTALL_TOKEN"
      $fileContent = Get-Content $ENVOYEXPORT | Out-String
      $fileContentBytes = [System.Text.Encoding]::UTF8.GetBytes($fileContent)
      $fileContentEncoded = [System.Convert]::ToBase64String($fileContentBytes)
      Try {
            Invoke-RestMethod -Uri $url -Method Post -Body  @{ "data" = $fileContentEncoded; } -ContentType "multipart/form-data" -TimeoutSec 30
            Write-Output "Completed"
      } Catch {
            $ErrorMessage = $_.Exception.Message
            $FailedItem = $_.Exception.GetType().FullName
            Write-Output "Failed: $FailedItem - $ErrorMessage"
            echo "envoy"
      }
}
i see this error when I run script from PS>

File C:\temp\envoy\envoytest.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see "get-help about_signing" for more details.
At line:0 char:0
ASKER CERTIFIED SOLUTION
Avatar of oBdA
oBdA

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
done and should i run through .ps1?
Now run the envoy script again.
You are the best!! Kudos to oBdA!!