1

Not having much luck with my Powershell script, so any help would be great! What I'm trying to do is to reference from a test file that contains lines of usernames, and compare it to the Excel spreadsheet on column A1. If exists, it should blank out the username.

$users = Get-Content "E:\temp\test.txt"
foreach ($user in $users) {

    set-aduser $user -fax " "

    $answer1 = read-host "Please Make a Selection"  
    if ($answer1 -eq 1){ 
        $location="Melbourne"
    }  
    if ($answer1 -eq 2){ 
        $location="Sydney"
    }
    if ($answer1 -eq 3){ 
        $location="Adelaide"
    }
    if ($answer1 -eq 4){ 
        $location="Brisbane"
    }
    if ($answer1 -eq 5){ 
        $location="Perth"
    }

    $ExcelPath = 'E:\temp\FX MFD UserPIN.xlsx'
    $Excel = New-Object -ComObject Excel.Application
    $Excel.Visible = $true
    $ExcelWorkBook = $Excel.Workbooks.Open($ExcelPath)
    $ExcelWorkSheet = $Excel.WorkSheets.item("$location")


    $Range = $ExcelWorkSheet.Range("A1").EntireColumn
    $Search = $Range.find($user)

    If($Search.value() -contains $user) 
    {

        Write-Host "User FOUND, removing now"
        $Search.value() = ""
    }
    else {
        Write-Host "User NOT FOUND"
    }
}

Error code is this:

You cannot call a method on a null-valued expression.
At E:\temp\testsest.ps1:35 char:12
+         If($Search.value() -contains $SearchString)
 +            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull

How do I replace the $Search to get $user?

Kelvin
  • 11
  • 1
  • 2
  • 2
    looks like $Range.find($user) returns null. You should check that or provide a piece of your excel sheet. – Martin Brandl Jul 10 '15 at 06:53
  • Check the post from Vesper about the null-valued expression exception: http://stackoverflow.com/questions/31335195/you-cannot-call-a-method-on-a-null-valued-expression-general – Martin Brandl Jul 10 '15 at 08:12

2 Answers2

4

Range.Find() returns Nothing if no match is found.

Therefore, before you check if there is a match, you have to check if there's a null value in $Search.

if ($Search -ne $null) { 
    if ($Search.value -contains $user) 
    {
        Write-Host "User FOUND, removing now"
        $Search.value = ""
    }
    else {
        Write-Host $Search.value," what did we find?!"
    }
}
else {
    Write-Host "User NOT FOUND"
}

Also, value is not a method, it's a property, so don't use round brackets.

Vesper
  • 18,599
  • 6
  • 39
  • 61
0

Thanks Vesper. I've made a couple more changes and can confirm it works now.

if ($Search -ne $null) { 

        if ($Search.text -contains $user) 
        {
           Write-Host "User FOUND, removing now"
           $Range.replace($Search,"")
        }
        else {
            Write-Host $Search.text," what did we find?!"
        }
    }
    else {
        Write-Host "User NOT FOUND"
    }
Kelvin
  • 11
  • 1
  • 2