Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

powershell script- need help-

Posted on 2016-11-23
30
Medium Priority
?
116 Views
Last Modified: 2016-11-28
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

0
Comment
Question by:abcd ab01
  • 18
  • 5
  • 3
30 Comments
 
LVL 71

Expert Comment

by:Qlemo
ID: 41899919
Do you see the progress messages written to the PS console?
0
 

Author Comment

by:abcd ab01
ID: 41899921
what do you meant by?
0
 

Author Comment

by:abcd ab01
ID: 41899923
I'm confused by the following , may be I'm wrong
0
Lessons on Wi-Fi & Recommendations on KRACK

Simplicity and security can be a difficult  balance for any business to tackle. Join us on December 6th for a look at your company's biggest security gap. We will also address the most recent attack, "KRACK" and provide recommendations on how to secure your Wi-Fi network today!

 

Author Comment

by:abcd ab01
ID: 41899924
"OU=rti,OU=Depts,OU=Dept 58,OU=Users,DC=DC02,DC=contoso,DC=com"
0
 

Author Comment

by:abcd ab01
ID: 41899927
our users folder is under> domain controller> dc02, domain name> contoso.com, OU-rti\Depts\users

please help me
0
 
LVL 71

Expert Comment

by:Qlemo
ID: 41899931
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.
0
 
LVL 71

Expert Comment

by:Qlemo
ID: 41899932
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.
0
 

Author Comment

by:abcd ab01
ID: 41899933
is this correct?
OU=OU-rt
0
 

Author Comment

by:abcd ab01
ID: 41899937
can we do remote session if possible?
I dont see its creating any list in the c:\temp\envoy2?
what to check?
0
 

Author Comment

by:abcd ab01
ID: 41900012
this scrip is basically for envoy to sysnc up with AD
0
 
LVL 85

Expert Comment

by:oBdA
ID: 41900364
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.
0
 

Author Comment

by:abcd ab01
ID: 41900678
When I'm done with this thread, is there any way to delete the code?
0
 

Author Comment

by:abcd ab01
ID: 41900830
Please remove domain name and ou names
0
 

Author Comment

by:abcd ab01
ID: 41901831
Great!! That's ok thanks a lot!!!
0
 

Author Comment

by:abcd ab01
ID: 41901837
One more request- please change wherever you see- dco2, rti and envoy2
0
 

Author Comment

by:abcd ab01
ID: 41901989
Thank u!
0
 

Author Comment

by:abcd ab01
ID: 41903674
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?
0
 
LVL 85

Expert Comment

by:oBdA
ID: 41903700
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.
0
 

Author Comment

by:abcd ab01
ID: 41904687
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
0
 
LVL 85

Expert Comment

by:oBdA
ID: 41904693
Don't paste the script into a PS console. Save it as envoy-ad-sync.ps1 or Whatever.ps1 to test it.
0
 

Author Comment

by:abcd ab01
ID: 41904715
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"
      }
}
0
 

Author Comment

by:abcd ab01
ID: 41904718
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
0
 
LVL 85

Accepted Solution

by:
oBdA earned 2000 total points
ID: 41904725
Open an administrative Powershell console and enter
Set-ExecutionPolicy -ExecutionPolicy Bypass -Force

Open in new window

0
 

Author Comment

by:abcd ab01
ID: 41904733
done and should i run through .ps1?
0
 
LVL 85

Expert Comment

by:oBdA
ID: 41904750
Now run the envoy script again.
0
 

Author Closing Comment

by:abcd ab01
ID: 41904755
You are the best!! Kudos to oBdA!!
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Recently we ran in to an issue while running some SQL jobs where we were trying to process the cubes.  We got an error saying failure stating 'NT SERVICE\SQLSERVERAGENT does not have access to Analysis Services. So this is a way to automate that wit…
In this post, I will showcase the steps for how to create groups in Office 365. Office 365 groups allow for ease of flexibility and collaboration between staff members.
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
Screencast - Getting to Know the Pipeline

916 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question