Exporting mailadressen to CSV - powershell

I want our Marketing deparment to extract all mailadressen from our users to CSV.
I created and Constrained Endpoint by using a configuration file, but i keep getting errors
First i created the config file:
New-PSSessionConfigurationFile -Path 'c:\marketing.pssc' -SessionType 'RestrictedRemoteServer' -LanguageMode FullLanguage -ModulesToImport ActiveDirectory -VisibleCmdlets ('Get-ADUser', 'Get-ADGroupMember', 'Export-Csv', 'Select-Object')
Register-PSSessionConfiguration –Name ‘Marketing’ -ShowSecurityDescriptorUI –Path ‘c:\marketing.pssc’
Im trying to run this code:
Set-ExecutionPolicy remotesigned -Scope Process -Force
$session = New-PSSession -ComputerName name -ConfigurationName 'marketing'
Invoke-Command -Session $session -Scriptblock {
Get-ADGroupMember -Identity "groupname" -Recursive | Get-ADUser -Properties Mail | where {$_.mail -ne $null} | Select Name,Mail | Export-CSV -Path "\\somepathto\file.csv" -NoTypeInformation
}
Remove-PSSession $session
i Expect an CSV file with name and email adressen.
The script works when running as a domain admin, currently i get this error:
The term 'where.exe' is not recognized as the name of a cmdlet, function, script file, or operable program....

According to the get-aduser commandlet, you should provide at least a required input param. Currently, it is stating the one you provide(-properties) is not approved by the validateset of the input param set.
https://learn.microsoft.com/en-us/powershell/module/addsadministration/get-aduser?view=win10-ps
This will help you out:
Get-ADUser -LDAPFilter '(mail=*marketing)' | select-object Name,Mail
https://ss64.com/ps/get-aduser.html

Related

Powershell Get-Childitem in ISE

please can you help me.
I'm missing some information.
Why when I execute the code:
Invoke-Command -ComputerName domainpc -ScriptBlock {Get-ChildItem -path C:\Users -Filter "username1"}
the result is: username1
And when I execute this script:
$user = Read-Host "Please enter username"
Invoke-Command -ComputerName domainpc -ScriptBlock {Get-ChildItem -path C:\Users -Filter "$user"}
the result is a list of folder contained in C:\Users
I don't understand why executing script get different results than execute code without variable.
Seems that the problem is the variable.
Please can you explain this?
Thanks.
You are hitting scope "problems".
The variable $user inside your script block -ScriptBlock is not known.
Take a look here: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_remote_variables?view=powershell-7.1#using-local-variables
Use $Using:user to get around.

Saving Active Directory Configuration settings to a file

I'm using my machine to run a script on the Domain Controller server using Enter-PSSession. It all works except, I can't save the outputs from the script on my local machine.
I want to save the outputs from the script as objects in my local machine in a csv format (Not on the Domain Controller server).
What I'm trying to do is save results from running commands like Get-ADDomainController etc..
Can someone please help me with this?
As for this …
I can't save the outputs from the script on my local machine.
… sure you can. Just create a log file as part of your session and copy that file back to your workstation for review, or just use the *-Transcript cmdlets to that creates a file automatically that you can copy over. The transcript will record everything that happens in the sessions.
Get-Command -Name '*transcript*' | ft -a
CommandType Name Version Source
----------- ---- ------- ------
Cmdlet Start-Transcript 3.0.0.0 Microsoft.PowerShell.Host
Cmdlet Stop-Transcript 3.0.0.0 Microsoft.PowerShell.Host
# get function / cmdlet details
(Get-Command -Name Start-Transcript).Parameters
Get-help -Name Start-Transcript -Full
Get-help -Name Start-Transcript -Online
Get-help -Name Start-Transcript -Examples
Or, don't use the interactive Enter-PSSession (explicit PowerShell Remoting) that puts you directly on the DC. Use a Implicit PSRemoting session, using New-PSSession and proxy the AD cmdlets to your machine for use.
$SessionAD = New-PSSession -ComputerName ''dc01.contoso.com
Invoke-Command $SessionAD -Command {Import-Module ActiveDirectory}
Import-PSSession $SessionAD -Module ActiveDirectory | Out-Null
$ADUSers = Get-ADuser -Filter *
$var = $ADUSers | Select-Object -Property Name, SamaccountName | Out-GridView -OutputMode Single
$GroupsMember = Get-ADUser -Filter ('Name -eq "' + $var.Name + '"') -Property MemberOf |
Select -ExpandProperty MemberOf |
Get-ADGroup -Property MemberOf |
Select Name
$GroupsMember
Get-PSSession | Remove-PSSession
Then you can run ADDS cmdlets as if they are actually on your machine and results are on your machine, or if you are on Window 8 or higher, just download and install (Win 7 - 8) / enable the RSAT tools (Win 10) directly and use them.
Remoting the Implicit Way
PowerShell Implicit Remoting: Never Install a Module Again
Also, take a look and Invoke-Command for running command locally or remotely.

How to write local variable to a file in remote server using Powershell script?

On a remote server there is a .BAT file which uses a .properties file to run.
I am able to run the .BAT file calling the .properties file, but in that .properties file last line is:
exportQuery1=SELECT * FROM CI_INFOOBJECTS where SI_ID='123456'.
I am modifying that line/SI_ID value manually which actually increasing my effort.
I have tried a few options but am not able to provide the value/entire line from the local powershell commandline which will be written in the .properties file.
So I have to modify the .ps1 every time. I want to pass the entry with the local powershell command as a variable.
Deleting the old line:
Invoke-Command -computername $ServerName -Credential $Cred -ErrorAction stop -ScriptBlock {Set-Content -Path D:\Script\TestFile.txt -Value (get-content -Path D:\Script\TestFile.txt | Select-String -Pattern 'SI_ID' -NotMatch)}
Creating the New line at the end of the file:
Invoke-Command -computername $ServerName -Credential $Cred -ErrorAction stop -ScriptBlock {add-content D:\Script\TestFile.txt "exportQuery1=SELECT * FROM CI_INFOOBJECTS where SI_ID='abcdef'"}
Please help to pass the SI_ID/entire line from the command while executing the script.
Why not use a simple parameter and the using statement in a single invoke call?
param($SI_ID)
$SB = {
Set-Content -Path D:\Script\TestFile.txt -Value (get-content -Path D:\Script\TestFile.txt | Select-String -Pattern 'SI_ID' -NotMatch)
add-content D:\Script\TestFile.txt "exportQuery1=SELECT * FROM CI_INFOOBJECTS where SI_ID='$using:SI_ID'"
}
Invoke-Command -computername $ServerName -Credential $Cred -ErrorAction stop -ScriptBlock $SB
then just .\myscript -SI_ID "abcd"

Why am i receiving RPC server is unavailable error when looping?

I have a Powershell script to find specific servers and their corresponding service accounts. If I modify the script to use a single server and a single service account, the results are what I expect. If I loop thru the servers and accounts, I receive the following error:
#################################################################
# Find Service Account(s) used to start Services on a Server(s) #
#################################################################
$accounts = (Get-Content C:\Users\location\Scripts\Service_Accounts.txt)
Remove-Item -path C:\Users\location\Scripts\ServiceAccountFnd.txt -force -erroraction silentlycontinue
Import-Module ActiveDirectory # Imports the Active Directory PowerShell module #
## Retrieves servers in the domain based on the search criteria ##
$servers=Get-ADComputer -Filter {Name -Like "namehere*"} -property *
## For Each Server, find the services running under the user specified in $account ##
ForEach ($server in $servers) {
Write-Host $server
ForEach ($account in $accounts) {
Write-Host $account
Get-WmiObject Win32_Service -ComputerName $server | Where-Object {$_.StartName -like "*$account*"} | Format-Table -HideTableHeaders -property #{n='ServerName';e={$_.__SERVER}}, StartName, Name -AutoSize | Out-File -FilePath C:\Users\location\Scripts\ServiceAccountFnd.txt -append -Width 150
}
}
Your $server variable does not only contain the hostname, but also all attributes of the AD computer object.
Try to change the ComputerName value to $server.name.
If that doesn't help: Can you confirm, that you used the very same computer in the loop as without the loop, as you described? I'd assume that you try to access another computer, which is not configured as expected.
Besided that, I'd recommend you to use Get-CimInstance rather than Get-WmiObject, as it doesn't use RPC, but WinRM by default. WinRM is more firewall friendly, secure and faster.

Pass variables to the remotely imported powershell module

I am trying to create new PSSession, import ActiveDirectory module on the remote machine and then import-pssession to my local workstation - this works fine. The code looks like:
$rs = New-PSSession -ComputerName RemoteMachine
Invoke-Command -Session $rs -scriptblock {import-module ActiveDirectory}
Import-PSSession -Session $rs -Module Active Directory
And now I am able to call ActiveDirectory cmdlets, so e.g. Get-ADUser -Filter * works fine.
BUT
I am not able to pass variables to the ActiveDirectory cmdlets, I am not able to execute the following:
$name = 'John Smith'
Get-ADUser -Filter {name -eq $name}
It says $name is not defined. I cannot pass the variable to the Get-ADUser.
Any suggestions?
Thanks
I can't test it now but try to use double quotes instaed of a script block so the value of the variable can be expanded before it moves on to the target,
Get-ADUser -Filter "name -eq $name"