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?
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.
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"
}
Related
I have PowerShell script which access the AD users and insert into the SharePoint list.
Now the problem is some of the accounts are disabled or not active. I am using the following PowerShell script in the windows task scheduler which do the job in an interval. Can anyone Help me to figure out What I suppose to do in this script to filter only active accounts?
#if not already added
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}
$site = new-object Microsoft.SharePoint.SPSite("https://portal.company.gov.sa/");
$ServiceContext = [Microsoft.SharePoint.SPServiceContext]::GetContext($site);
#Get UserProfileManager from the My Site Host Site context
$ProfileManager = new-object Microsoft.Office.Server.UserProfiles.UserProfileManager($ServiceContext)
$AllProfiles = $ProfileManager.GetEnumerator()
# Open SharePoint List
$spWeb = Get-SPWeb "https://my.gac.gov.sa/"
$spData = $spWeb.GetList("Lists/EmployeesDirectory/")
$spDepartments = $spWeb.GetList("Lists/Departments/")
$total=0;
$withErros=0;
foreach($profile in $AllProfiles)
{
try
{
$DisplayName = $profile.DisplayName
$WorkEmail = $profile[[Microsoft.Office.Server.UserProfiles.PropertyConstants]::WorkEmail]
$AccountName = $profile[[Microsoft.Office.Server.UserProfiles.PropertyConstants]::AccountName]
$Department = $profile[[Microsoft.Office.Server.UserProfiles.PropertyConstants]::Department]
$Position = $profile.JobTitle
$LastName = $profile[[Microsoft.Office.Server.UserProfiles.PropertyConstants]::LastName]
$FirstName = $profile[[Microsoft.Office.Server.UserProfiles.PropertyConstants]::FirstName]
$FullName= "$FirstName $LastName"
$PreferredName = $profile[[Microsoft.Office.Server.UserProfiles.PropertyConstants]::PreferredName]
$WorkPhone =$profile[[Microsoft.Office.Server.UserProfiles.PropertyConstants]::WorkPhone]
$Manager = $profile[[Microsoft.Office.Server.UserProfiles.PropertyConstants]::Manager]
$JobTitleArabic=$profile["JobTitleArabic"];
if($Department -ine '' -and $Manager -ine ''){
$total++;
$departmnetItem = $spDepartments.Items | Where {$_["FF_TitleEn"] -eq $Department}
# Add properties to this list item
$user=$spWeb.EnsureUser($AccountName);
write-host $DisplayName "|" $AccountName "|" $Department "|" $Position "|" $PreferredName "|" $WorkPhone "|" $Manager ;
if($user.ID -gt 0)
{
#Query to filter List Items which contains user account
$SPQuery = new-object Microsoft.SharePoint.SPQuery
$Query = "<Where><Eq><FieldRef Name='FF_Emlpoyee' LookupId='TRUE'/><Value Type='User'>$($user.ID)</Value></Eq></Where>"
$SPQuery.Query=$Query
#Filter List Items by Query
$ListItems = $spData.GetItems($SPQuery)
if($ListItems.Count -gt 0)
{
$newItem=$ListItems[0];
}
else
{
#Create a new item
$newItem = $spData.Items.Add()
}
$newItem["FF_Emlpoyee"] = $user.ID;
# $newItem["FF_UserID"] = $user.ID;
$newItem["Title"] = $PreferredName
if($WorkPhone -ine '')
{
$newItem["FF_ExtensionNumber"] = $WorkPhone
}
try
{
if($Manager -ine $null)
{
$userManager=$spWeb.EnsureUser($Manager);
$newItem["FF_Manager"] = $userManager.ID
}
}
catch
{
write-host -ForegroundColor Red "Manager Not Found fro : " $user
}
$newItem["FF_Position"] = $Position
IF($JobTitleArabic -ine '')
{
$newItem["FF_PositionAr"] = $JobTitleArabic
}
$newItem["FF_FullNameAr"] = $FullName
$newItem["FF_Department"] = $departmnetItem.ID
$newItem.Update()
Write-Host "---------------------------------";
}
$user=$null
}
}
catch
{
write-host -ForegroundColor Red $_.Exception
$withErros+=1
}
}
Write-Host "Total: " $total;
Write-Host "withErros: " $withErros
$inventory = Import-Csv "E:\MonitoringScripts\HealthCheck\PatStat_Pshell\inventory.csv"
foreach ($line in $inventory) {
$server_name = $($line.servername)
$port_number = $($line.port)
$resolved_true = [System.Net.Dns]::GetHostAddresses("$server_name")
#Write-Host $resolved_true
if ($resolved_true) {
#Write-Host $server_name
Write-Host 'the host is resolving'
} else {
Write-Host 'Not found in DNS'
}
}
In the above code, how do I avoid the below content to appear in the command promt when there is a host in the inventory file which is not resolving the dns?
Exception calling "GetHostAddresses" with "1" argument(s): "No such host is
known"
At E:\MonitoringScripts\HealthCheck\PatStat_Pshell\patrol.ps1:9 char:2
+ $resolved_true = [System.Net.Dns]::GetHostAddresses("$server_name")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SocketException
Not found in DNS
the host is resolving
I just want to see:
Not found in DNS
or
the host is resolving
Catch the exception:
try {
[Net.Dns]::GetHostAddresses($server_name)
Write-Host 'the host is resolving'
} catch {
Write-Host 'Not found in DNS'
}
Read About Try Catch Finally:
Use Try, Catch, and Finally blocks to respond to or handle terminating
errors in scripts.
You can apply it as follows:
try {
$resolved_true = [System.Net.Dns]::GetHostAddresses($server_name)
} catch {
$resolved_true = $null
}
Test-Connection to see if the host exists first. Of course, the host existing is not exactly the same thing as finding it in DNS.
$inventory = import-csv “E:\MonitoringScripts\HealthCheck\PatStat_Pshell\inventory.csv”
ForEach ($line in $inventory)
{
$server_name = $($line.servername)
$port_number = $($line.port)
$resolved_true = $null
if (Test-Connection -ComputerName $server_name -ErrorAction SilentlyContinue) {
$resolved_true = [System.Net.Dns]::GetHostAddresses("$server_name")
}
#Write-host $resolved_true
if($resolved_true) {
#write-host $server_name
Write-Host 'the host is resolving'
} else {
Write-Host 'Not found in DNS'
}
}
$inventory = import-csv “E:\MonitoringScripts\HealthCheck\PatStat_Pshell\inventory.csv”
ForEach ($line in $inventory)
{
$server_name = $($line.servername)
$port_number = $($line.port)
$resolved_true = $null
try {
$resolved_true = [System.Net.Dns]::GetHostAddresses($server_name)
} catch {
$resolved_true = $null
}
#Write-host $resolved_true
if($resolved_true) {
#write-host $server_name
Write-Host 'the host is resolving'
} else {
Write-Host 'Not found in DNS'
}
}
This worked for me, Thank you so much all for the help.
I will have to mark #JosefZ Answer, But really thank you all.
I'm working on a PowerShell script for some work use, and am having trouble getting a function it's data directly to a variable. Below is the function and my test:
function validateInput {
Param(
[string]$Text = 'Put text here'
)
do {
try {
$numOk = $true
$GetMyANumber = Read-Host "$text"
if ($GetMyANumber -gt 3){
$numOK = $false
}
} catch {
$numOK = $false
}
if ($numOK -ne $true) {
cls
Write-Host "Please enter a valid number" -Foreground Red
}
} until (($GetMyANumber -ge 0 -and $GetMyANumber -le 3) -and $numOK)
}
$firstName = validateInput($firstNamePrompt)
$lastName = validateInput ($lastNamePrompt)
Write-Host "First name length is $firstname"
Write-Host "Last name length is $lastname"
My understanding is that the in the last few lines, the function SHOULD assign it's output to the variables $firstName and $lastName, but I output that, they are blank. I'm sure I'm missing something obvious here, but can anyone let me know what I'm screwing up?
I am writing a powershell script to manage our local administrator accounts using a csv file.
#variable to store the data in data.csv
$userobjects = Import-CSV C:-data.csv
function main-list{
Write-Host "--------------------------------------"
Write-Host "Windows Powershell Account Manager"
Write-Host "--------------------------------------"
Write-Host "1 - Change Name"
Write-Host "2 - Disabled Account"
Write-Host "3 - Delete User"
Write-Host "4 - Exit"
[int]$action = Read-Host "Enter the menu number from above"
if ($action -eq 1){change-name}
if ($action -eq 2){disable-account}
if ($action -eq 3){delete-user}
if ($action -eq 4){cls; break}
}
function change-name
{
foreach ($user in $userobjects)
{
#Assign the content to variables
$FileHostname = $user.Host
$FileAccount = $user.Account
$FileNewname = $user.Rename
$FileDisable = $user.Disable
$FileDelete = $user.Delete
# Rename
if (($user.Account -ne $user.Rename) -and ($user.Rename -ne '' ))
{
#Write-Host "old name :"$FileHostname"/"$FileAccount "-> new name :"$FileHostname"/"$FileNewname
$connection = $FileHostname+"/"+$FileAccount
$accName = [ADSI]("WinNT://$connection")
if ($accName.path -eq "WinNT://"+$connection+"")
{
$accName.psbase.Rename($FileNewname)
Write-Host "Account(s) renamed"
$user.Account = $user.Rename
}
else
{
Write-Host "Account name :"$connection "can't be found on the host"
}
$user.Account = $user.Rename
$userobjects | export-csv C:-data.csv -notype
}
}
Write-Host "--------------------------------------"
main-list
}
function disable-account
{
foreach ($user in $userobjects)
{
#Assign the content to variables
$FileHostname = $user.Host
$FileAccount = $user.Account
$FileNewname = $user.Rename
$FileDisable = $user.Disable
$FileDelete = $user.Delete
if ($user.Disable -eq 'yes')
{
$connection = $FileHostname+"/"+$FileAccount
$accName = [ADSI]("WinNT://"+$connection+"")
if ($accName.UserFlags -eq '515')
{
Write-Host "Account :"$connection "is already disabled"
}
else
{
$accName.description = "Account disabled"
$accName.UserFlags = 2
$accName.setinfo()
Write-Host "Account(s) disabled"$connection
}
}
}
Write-Host "--------------------------------------"
main-list
}
function delete-user
{
foreach ($user in $userobjects)
{
#Assign the content to variables
$FileHostname = $user.Host
$FileAccount = $user.Account
$FileNewname = $user.Rename
$FileDisable = $user.Disable
$FileDelete = $user.Delete
#Delete
if ($user.Delete -eq 'yes')
{
$connection = $FileHostname+"/"+$FileAccount
$accName = [ADSI]("WinNT://"+$connection+"")
$accName.delete("user",$accName.name)
#Write-Host $connection deleted
}
else
{
Write-Host "Account name :"$connection "can't be found on the host"
}
}
}
}
$userobjects | export-csv C:-\data.csv -notype
main-list
I don't really know why I have this message when I am trying to use the delete function : "Unknown name", it is like it doesn't find the local account to delete it but I am not sure. However, It works perfectly when I want to rename or disable accounts.
My data file looks like that
http://www.noelshack.com/2016-05-1454622367-capture.png
I will post the real message when I will be back to work tomorow.
Thank you for your help.
Quick skim... wouldn't this need to be used instead? I think your $accName.name would be using the machine name.
$accName.delete("user",$user.account)
You delete() the user from the computer, so your [adsi] object should bind to the computer and call Delete() on that instead:
# Just the machine name, nothing more:
$Machine = [ADSI]"WinNT://$FileHostname"
# Now delete the user account from the machine
$Machine.Delete('user',$FileAccount)
Below is the script I want to execute. The issue here is once an exception occurs it stops executing, I used continue in the catch block but that did not work. How do I get it working even after an exception occurs it should loop in foreach.
I also used a while($true) loop but that went into infinite loop. How to go about it?
$ErrorActionPreference = "Stop";
try
{
# Loop through each of the users in the site
foreach($user in $users)
{
# Create an array that will be used to split the user name from the domain/membership provider
$a=#()
$displayname = $user.DisplayName
$userlogin = $user.UserLogin
# Separate the user name from the domain/membership provider
if($userlogin.Contains('\'))
{
$a = $userlogin.split("\")
$username = $a[1]
}
elseif($userlogin.Contains(':'))
{
$a = $userlogin.split(":")
$username = $a[1]
}
# Create the new username based on the given input
$newalias = $newprovider + "\" + $username
if (-not $convert)
{
$answer = Read-Host "Your first user will be changed from $userlogin to $newalias. Would you like to continue processing all users? [Y]es, [N]o"
switch ($answer)
{
"Y" {$convert = $true}
"y" {$convert = $true}
default {exit}
}
}
if(($userlogin -like "$oldprovider*") -and $convert)
{
LogWrite ("Migrating User old : " + $user + " New user : " + $newalias + " ")
move-spuser -identity $user -newalias $newalias -ignoresid -Confirm:$false
LogWrite ("Done")
}
}
}
catch {
LogWrite ("Caught the exception")
LogWrite ($Error[0].Exception)
}
You use try {...} catch {...} when you want to handle errors. If you want to ignore them, you should set $ErrorActionPreference = "Continue" (or "SilentlyContinue") as #C.B. suggested, or use -ErrorAction "SilentlyContinue" for the particular operation raising the error. If you want to handle errors from a certain instruction, you'd put that instruction in the try {...} catch {...} block, not the entire loop, e.g.:
foreach($user in $users) {
...
try {
if(($userlogin -like "$oldprovider*") -and $convert) {
LogWrite ("Migrating User old : " + $user + " New user : " + $newalias + " ")
move-spuser -identity $user -newalias $newalias -ignoresid -Confirm:$false
LogWrite ("Done")
}
} catch {
LogWrite ("Caught the exception")
LogWrite ($Error[0].Exception)
}
}
You seem to have placed the "catch" outside the loop body, so that aborts the loop. Put the catch inside the loop
Modified the code as below. Used the following piece of code after move-spuser -identity $user -newalias $newalias -ignoresid -Confirm:$false
if($?)
{
LogWrite ("Done!")
LogWrite (" ")
}
else
{
LogWrite ($Error[0].ToString())
LogWrite (" ")
}
Something that worked for me is to set the $ErrorActionPreference variable to stop, and then reset it back to continue in the catch block:
$e = $ErrorActionPreference
$ErrorActionPreference="stop"
try
{
#Do Something that throws the exception
}
catch
{
$ErrorActionPreference=$e
}
$ErrorActionPreference=$e;