How to fix A null key is not allowed in a hash literal in PowerShell - powershell

I been following this Microsoft doc https://learn.microsoft.com/en-us/powershell/module/exchange/search-unifiedauditlog?view=exchange-ps and I'm trying to write a PowerShell Script that download Audit Log. So far everything is going well but I'm just wondering how can I read User Id from my csv file instead of having a user Id directly in my script?.
This is how my CSV file look right now.
C:\AuditLogSearch\Reference\User.csv
Name Email Id
................................
1. Ronaldo ronaldo#gmail.com KLIEKN
2. Messi messi#gmail.com LEK89K
3. LeBron lebron#gmail.com IKNLM9
I was hard coding like this in the script and it's working fine but
$Global:user = "KLIEKN", "LEK89K", "IKNLM9",
Search-UnifiedAuditLog -SessionId $sessionID -SessionCommand ReturnLargeSet -UserIds $user
I don't think that'll be good idea so I try to do read it from my CSV file like this
$Global:userPath = "C:\AuditLogSearch\Reference\User.csv"
function Log-Search {
Import-Csv $userPath | ForEach-Object -Property #{
$userId = $($_.Id)
}
Search-UnifiedAuditLog -SessionId $sessionID -SessionCommand ReturnLargeSet -UserIds $userId
}
but I'm getting this error
A null key is not allowed in a hash literal.
I'll be really appreciated any help or suggestion.

{} defines a [ScriptBlock] — which is what you'd pass to the ForEach-Object cmdlet to be invoked for each element — whereas #{} defines a [Hashtable]. $userId is $null because you have not assigned a value, so where you have...
#{
$userId = $($_.Id)
}
...you are trying to define a [Hashtable] with an element with a key of $null, hence the error.
There is also no such -Property parameter of ForEach-Object, so when you remove "-Property #", you end up with a valid script...
Import-Csv $userPath | ForEach-Object {
$userId = $($_.Id)
}
This is reading your CSV file but not yet passing the data to your Search-UnifiedAuditLog call. There are several ways to retrieve the Id field of each CSV record, but the shortest transformation from the previous snippet would be...
Import-Csv $userPath | ForEach-Object {
$_.Id
}
...which can be rewritten using the -MemberName parameter...
Import-Csv $userPath | ForEach-Object -MemberName Id
...and then all that's left is to store the pipeline results in $userId...
$userId = Import-Csv $userPath | ForEach-Object -MemberName Id
By the way, the CSV data you posted cannot be readily parsed by Import-Csv. If possible, save your data without the second line and using comma or tab as the delimiter (the latter being read with Import-Csv ... -Delimiter "`t"); otherwise, the script will have to do some manipulation before it can read the data.

Try this perhaps?
$userId=#()
Import-Csv $userPath | ForEach-Object {
$userId += $_.Id
}
or
$userId = Import-Csv $userPath | Select-Object -ExpandProperty Id

Related

Working with a list of AD 'displayNames' in Powershell. How to indicate which users were not found?

I have written enough PS code to go through a list of displayNames (e.g "John Smith", "Taylor Hanson" - all stored on seperate lines of a txt file) to spit back enough data into another text file that can be used for mailmerge etc. Convincing thousands of employees to simply update Windows is like breaking stones! It has to be automatted to some degree...
Here is the code... the functions that let the user open a specific text file and later save are out of view...
$displayname = #()
$names = get-content $FileIN
foreach ($name in $names) {
$displaynamedetails = Get-ADUser -filter { DisplayName -eq $name } | Select Name, GivenName, Surname, UserPrincipalName
$displayname += $displaynamedetails
}
$displayname | Export-Csv -NoTypeInformation -path $fileOUT -Encoding UTF8
From time to time, a name might be spelled incorrectly in the list, or the employee may have left the organisation.
Is there any way that a statement such as 'Not Found' can be written to the specific line of the text file if an error is ever made (so that an easy side-by-side comparison of the two files can be made?
For most of the other solutions I've tried to find, the answers are based around the samAccoutName or merging the first and last names together. Here, i am specifically interested in displaynames.
Thanks
You can give this a try, since -Filter or -LDAPFilter don't throw any exception whenever an object couldn't be found (unless you're feeding a null value) you can add an if condition to check if the variable where the AD User object is going to be stored is not null and if it is you can add this "not found" user into a different array.
$domain = (Get-ADRootDSE).DefaultNamingContext
$names = Get-Content $FileIN
$refNotFound = [System.Collections.Generic.List[string]]::new()
$displaynamedetails = foreach($name in $names)
{
if($aduser = Get-ADUser -LDAPFilter "(DisplayName=$name)")
{
$aduser
continue
}
$refNotFound.Add(
"Cannot find an object with DisplayName: '$name' under: $domain"
)
}
$displaynamedetails | Select-Object Name, GivenName, Surname, UserPrincipalName |
Export-Csv -NoTypeInformation -path $fileOUT -Encoding UTF8
$refNotFound # => Here are the users that couldn't be found
Side note, consider stop using $displayname = #() and += for well known reasons.
As for AD Cmdlets, using scriptblock based filtering (-Filter {...}) is not supported and even though it can work, it can also bring you problems in the future.

Powershell: delete duplicate entry in arraylist

In my Powershellscript I read some data from a csv-File in an Arraylist.
In the second step I eliminate every line without the specific char: (.
At the third step I want to eliminate every double entries.
Example for my list:
Klein, Jürgen (Klein01); salesmanagement national
Klein, Jürgen (Klein01); salesmanagement national
Meyer, Gerlinde (Meyer02); accounting
Testuser
Admin1
Müller, Kai (Muell04); support international
I use the following script:
$Arrayusername = New-Object System.Collections.ArrayList
$NewArraylistuser = New-Object System.Collections.ArrayList
$Arrayusername = Get-Content -Path "C:\Temp\User\Userlist.csv"
for ($i=0; $i -le $Arrayusername.length; $i++)
{
if ($Arrayusername[$i] -like "*(*")
{
$NewArraylistuser.Add($Arrayusername_ads[$i])
}
$Array_sorted = $NewArraylistuser | sort
$Array_sorted | Get-Unique
}
But the variable $Array_sorted still has double entries.
I don´t find the mistake.
Some Ideas how you could change your code:
Use the existing Command to import .csv files with the Delimiter ;.
Filter the output with Where-Object to only include Names with (.
Select only unique objects with Select-Object, or if you want to sort the Object, use the Sort-Object with the same paramets.
Something like this should work:
Import-csv -Delimiter ';' -Header "Name","Position" -Path "C:\Temp\User\Userlist.csv" | Where-Object {$_.Name -like "*(*"} | Sort-Object -Unique -Property Name,Position

CSV export is missing data in one of the columns

I have a csv file that this script works fine on.
$CCure = Import-csv C:\Scripts\file1.csv
ForEach ($user in $CCure) {
[string]$1Name = $User.FirstName
[string]$2Name = $User.LastName
[string]$GivenName = $1Name.Split(" ")[0]
[string]$SN = $2Name.Split(",")[0]
[string]$ID = $User.ObjectID
[string]$EmpID = $User.Int5 |
Select #{Name="First Name";Expression={$GivenName}}, #{Name="Last Name";Expression={$SN}}, #{Name="CCure ObjectID";Expression={$ID}}, #{Name="CCure Int5 Row";Expression={$EmpID}} |
Export-csv C:\Scripts\CCure\CCure-Names-Test.csv -Append -notypeinformation
}
However, when I try a similar script going out to AD and want to use RegEx, things don't work. It seems to hang or when it does run, the SurName is missing. Why doesn't the second one work? I must be missing something simple?
$Users = Get-ADUser -LDAPFilter "(&(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2))" -properties samaccountname,givenname,sn
ForEach ($User in $Users) {
[string]$1Name = $User.GivenName
[string]$2Name = $User.SN
[string]$GivenName = $1Name.Split(" ")[0]
[string]$SN = $2Name.Split(",")[0] |
Select #{Name="First Name";Expression={$GivenName}}, #{Name="Last Name";Expression={$SN}},#{Name="SID";Expression={$User.samaccountname}}| Export-Csv C:\scripts\ccure\AD-Active-Names3.csv -NoTypeInformation -append
}
In your second example $sn would be null. This is because of the trailing pipe character that you have. This issue is also present in your first code block for $EmpID. The last command Export-CSV returns nothing to the output stream so the variable in both cases would be $null.
You are taking the result of $2Name.Split(",")[0] and sending that into the pipeline which is then left unused for Select-Object.
So the simple answer is remove the pipeline character and those two lines will now work separately.
[string]$SN = $2Name.Split(",")[0]
Select #{Name="First Name";Expression={$GivenName}}, #{Name="Last Name";Expression={$SN}},#{Name="SID";Expression={$User.samaccountname}}| Export-Csv C:\scripts\ccure\AD-Active-Names3.csv -NoTypeInformation -append
Also consider making your own object if you are changing property names and values that much. This should accomplish the same thing, be easier to read and take advantage of the pipeline.
$Users = Get-ADUser -LDAPFilter "(&(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2))"
$Users | ForEach-Object {
$props = #{
"First Name" = ($_.GivenName).Split(" ")[0]
"Last Name" = ($_.SurName).Split(",")[0]
"SID" = $_.samaccountname
}
New-Object -TypeName psobject -Property $props
} | Select-Object "First Name","Last Name",SID | Export-Csv C:\scripts\ccure\AD-Active-Names3.csv -NoTypeInformation
You will note that I used $_.SurName as the property names used since PowerShell AD Objects do not directly match their LDAP attribute names. If you tried to access $_.SN you would get a null value. GivenName,Surname and SID are part of the value set returned by default so you don't need to request them.
Looking at about_ActiveDirectory_ObjectModel you will see under AdUser:
Surname - A property of type System.String, derived from the directory attribute: sn
You will still get errors with this if Surname or GivenName are not populated. Accounting for that would be a simple if statement if that is going to be an issue.

Export Powershell output to CSV

I have the following code intended to take a list of user names and output a CSV report of username - GroupMembership. At the command line the output looks great as i get "name" on the left and recursive "group memberships" on the right (see pic http://i.stack.imgur.com/zLxUR.jpg for command line output, sorry can't post imbedded Pics yet)
I would like to have the output written to a CSV file with the same format, namely Username in one column and GroupMemberships in the second column.. Original code from: http://thesurlyadmin.com/2013/03/21/get-a-users-group-memberships/ with a few small changes.
Param (
[Parameter(Mandatory=$true,ValueFromPipeLine=$true)]
[Alias("ID","Users")]
[string[]]$User
)
Begin {
Try { Import-Module ActiveDirectory -ErrorAction Stop }
Catch { Write-Host "Unable to load Active Directory module, is RSAT installed?"; Break }
}
Process {
ForEach ($U in $User)
{ $UN = Get-ADUser $U -Properties MemberOf
$Groups = ForEach ($Group in ($UN.MemberOf))
{ (Get-ADGroup $Group).Name
}
$Groups = $Groups | Sort
ForEach ($Group in $Groups)
{ New-Object PSObject -Property #{
Name = $UN.Name
Group = $Group
}
}
}
}
I tried using this "$PSObject | Export-CSV C:\Scripts\GroupMembershipList.csv" but it only writes the first line to the CSV and nothing after that.
Nate,
In Powershell v3.0, the Export-CSV cmdlet introduced the -Append parameter.
Reference: http://technet.microsoft.com/en-us/library/hh849932.aspx
Not knowing the version of Powershell you are using, this may require an update on your side to make use of the new functionality.
In my own cases, I generally see the opposite issue if I forget to -Append to my CSV; I will only end up with the LAST entry as opposed to just the first.
I won't claim this to be your fix, but might be worth a shot...
Example: $PSObject | Export-CSV C:\Scripts\GroupMembershipList.csv -Append

Issues with Powershell Import-CSV

Main Script
$Computers = Get-Content .\computers.txt
If ( test-path .\log.txt ) {
$Log_Successful = Import-CSV .\log.txt | Where-Object {$_.Result -eq "Succesful"}
} ELSE {
Add-Content "Computer Name,Is On,Attempts,Result,Time,Date"
}
$Log_Successful | format-table -autosize
Issues:
Log_Successful."Computer Name" works fine, but if i change 4 to read as the following
$Log_Successful = Import-CSV .\log.txt | Where-Object {$_.Result -eq "Failed"}
Log_Successful."Computer Name" no longer works... Any ideas why?
Dataset
Computer Name,Is On,Attempts,Result,Time,Date
52qkkgw-94210jv,False,1,Failed,9:48 AM,10/28/2012
HELLBOMBS-PC,False,1,Successful,9:48 AM,10/28/2012
52qkkgw-94210dv,False,1,Failed,9:48 AM,10/28/2012
In case of "Successful" a single object is returned. It contains the property "Computer Name". In case of "Failed" an array of two objects is returned. It (the array itself) does not contain the property "Computer Name". In PowerShell v3 in some cases it is possible to use notation $array.SomePropertyOfContainedObject but in PowerShell v2 it is an error always. That is what you probably see.
You should iterate through the array of result objects, e.g. foreach($log in $Log_Successful) {...} and access properties of the $log objects.
And the last tip. In order to ensure that the result of Import-Csv call is always an array (not null or a single object) use the #() operator.
The code after fixes would be:
$logs = #(Import-Csv ... | where ...)
# $logs is an array, e.g. you can use $logs.Count
# process logs
foreach($log in $logs) {
# use $log."Computer Name"
}
I'm not sure if this is the problem but you have a typo, in Where-Object you compare against "Succesful" and the value in the file is "Successful" (missing 's').
Anyway, what's not working?