Error – Import-Csv : Exception setting “Replace”: Object reference not set to an instance of an object

While running a Powershell script, faced below problem. If you get the same issue, check the CSV header names which you have used in Powershell to retrieve the csv data. Referring to a wrong name doesn’t give any error but throws error when you perform any action that variable.

E.g.

$supervisor = $_.Supervisor
$dept = $_.Dept

Error powershell-error1

Enjoy…

PowerShell – Update Active Directory User properties for multiple users

Requirement – Monthly once users details like Manager, Title, Working State etc. need to be updated in the active directory. User details will be shared through excel. To achieve that, PowerShell script was written.

Below is the excel Format, We Saved the file as Updated-Users.csv

powershell

And below is the working complete code for updating the user properties in AD

[Code type=”PowerShell”]

#—————————
# VARIABLES
#—————————

# Set $script:WhatIf = $true to prevent making changes to AD.
# Set $false to execute normally, making changes.
$script:WhatIf = $false

# Compute a string indicator
if ($script:WhatIf) { $strWhatif = “What If: “} else { $strWhatif = “” }
cls
Import-Module ActiveDirectory
<# Quest
Add-PSSnapin quest.activeroles.admanagement
#>

$department = $null
$Manager = $null
$file = New-Item -ItemType file C:\scripts\userAccountInfo.txt -Force

#—————————
# FUNCTIONS
#—————————

function parseManager([string] $m ){
# function takes a lastname, firstname MI string and parses to match manager info. returns email address.
if ($m -ieq “”)
{
return $null
}
else
{
$split = $m.split(” “)
$fn = $split[0]
$ln = $split[1]
#$splitfn = $fnmi.split(” “)
#$fn = $splitfn[1]
$fi = $fn.substring(0,1)
$em = $fi + $ln + “@healthgrades.com”
$validatedManager = checkManager($em)
return $validatedManager
}
}

function parseDept([string] $d){
$splitdept = $d.split(“-“)
$deptCode1 = $splitdept[0]
return $deptCode1
}

function checkManager ([string] $mg){

switch ($mg)
{
“ldisaverio@TestSites.com” { $mg = “ldisaver@TestSites.com”}
default { }
}

<# Quest
if (Get-QADUser -Identity $mg) {
return $mg
}

$mgid = $mg -replace ‘@TestSites.com’,”
if (Get-ADUser -Identity $mgid) {
return $mg
}

else
{
$updated = Read-Host “Manager $mg not found, please enter new Manager information”
$mg = checkManager $updated
return $mg
}
} # end function check Manager

function fnUpdateUsers(){

<#
The CSV has following default headers:
Payroll Name [Payroll Information],Preferred Name,Job Title,Work E-mail,dept,Location,Hire Date,Birth Date,Supervisor

It WAS required to change these to the following before processing:
Payroll Name [Payroll Information],Preferred Name,Title,email,dept,Location,HireDate,BirthDate,Supervisor

but now the script can recognize either set of headers, so it’s no longer required to change them
#>

Write-Host
Write-Host (“Processing Individual Users”)
Write-Host (“—————————“)

Import-Csv C:\scripts\updated-users.csv | foreach {

if ($_.”Work E-Mail”) { $email = $_.”Work E-Mail” } else { $email = $_.email }
if ($_.”Job Title”) { $title = $_.”Job Title” } else { $title = $_.Title }
if ($_.”Birth Date”) { $birthdate = $_.”Birth Date” } else { $birthdate = $_.BirthDate }
if ($_.”Hire Date”) { $hiredate = $_.”Hire Date” } else { $hiredate = $_.HireDate }
$supervisor = $_.Supervisor
$dept = $_.Dept
$dept = ([int]$_.Dept).ToString()

switch ($dept)
{
“110” { $department = “Corporate”}
“115” { $department = “Marketing”}
“118” { $department = “Product Management”}
default { $department = $null}
}

$name = $email -replace ‘@TestSites.com’,”
Write-Host (“Supervisor info: {0}” -f $supervisor)

$Manager = parseManager($supervisor)
Write-Host (“Supervisor info: {0}” -f $Manager)
$MgrName = $Manager -replace ‘@healthgrades.com’,”
Write-Host (“Supervisor info: {0}” -f $MgrName)
$MgrDN = (Get-ADUser $MgrName).DistinguishedName

Write-Host (“User info: {0}, {1}, {2}, {3}, Department: {4}” -f $email,$department,$title,$Manager,$dept)
try {
if ( $Manager -ne “”)
{
Set-ADUser -Identity $name -department $department -company “Test Company, Inc.” -Title $title -Description $title -Manager $MgrDN -WhatIf:($script:WhatIf)
Set-ADUser -Identity $name -replace @{hGCustomEmployeeBirthday = $birthdate} -WhatIf:($script:WhatIf)
Set-ADUser -Identity $name -replace @{hGCustomHireDate = $hiredate} -WhatIf:($script:WhatIf)
}
else {
Set-ADUser -Identity $email -department $department -Title $title -WhatIf:($script:WhatIf)
Set-ADUser -Identity $name -replace @{hGCustomEmployeeBirthday = $birthdate} -WhatIf:($script:WhatIf)
Set-ADUser -Identity $name -replace @{hGCustomHireDate = $hiredate} -WhatIf:($script:WhatIf)
}
}
catch [Exception] {
if ($_.Exception.Message -match “Cannot find an object with identity”) {
Write-Host -ForegroundColor Yellow (“Can’t find enabled user {0} in AD” -f $email)
}
else { throw $_.Exception }
}

#Add-Content $file “———————-”
Add-Content $file (“{0}User updated per CSV file: {1}” -f $strWhatif,$name)
#Add-Content $file “———————-”
#Add-Content $file ” ”
}
Add-Content $file “———————-”
Add-Content $file (“{0}Users updated per CSV file” -f $strWhatif)
Add-Content $file “———————-”
Add-Content $file ” ”
}
#—————————
# INVOKE MAIN FUNCTION
#—————————

fnUpdateUsers [/code]

Cheers…

SharePoint – Auto Populate value in Lookup fields using Query string parameter

Requirement –  There were two lists,  “Active jobs”, “Applied Jobs” . We had to place a “Apply job” link across every item in Active jobs list. On click of that link, it should take user to New form of “Applied Jobs” and Job Name from Active jobs should be auto populated in Applied Jobs new form.

Steps  – 

To set the Apply link with JobID parameter, we used workflow. On creation of item in Active Jobs, Link gets updated with link to New form of “Applied jobs” and appended with “JobID=”Current Item ID”.

In the “applied jobs” List >> Go to list >> Click on list tab >> Under customize list Category click on Modify Form Web parts >> add a Script editor and place this code.

<script type="text/javascript">
(function () {
 var ctx = {};
 ctx.Templates = {};
 ctx.Templates.Fields = {
 'Job_Name': {
 'NewForm': renderTaskCategory
 }
 };
 SPClientTemplates.TemplateManager.RegisterTemplateOverrides(ctx);
})();

function renderTaskCategory(ctx) {
 var jobId = GetUrlKeyValue('JobID'); //extract cat parameter from a query string
 ctx.CurrentFieldValue = jobId; //set lookup field value
 return SPFieldLookup_Edit(ctx); //default template for rendering Lookup field control
}
</script>

It gets populated when you click on apply link..

Cheers..

 

 

 

SharePoint – Make attachment field mandatory in the list

Requirement : There was a list where users fill in their details and need to attach their resume to the respective item. We had to make the attachment field mandatory so that every employee attaches the resume. Client dint want to create document library.

Follow below steps to implement the same

  1. Go to list >> Click on list tab >> Under customize list Category click on Modify Form Web parts >> add a Script editor and place this code. Basically we are overriding inbuilt PreSaveAction method .

If attachment not found, it will give an alert with message “Please attach resume”.

</pre>
<script type="text/javascript" language="javascript">
function PreSaveAction() {

var elm = document.getElementById("idAttachmentsTable");
 if (elm == null || elm.rows.length == 0)
{
 document.getElementById("idAttachmentsRow").style.display='none';
alert("Please attach resume");
return false ;
}
else { return true ;}
}
</script>

Cheers….