Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x

Powershell

15K

Solutions

7K

Contributors

Windows PowerShell is a task automation and configuration management framework from Microsoft, consisting of a command-line shell and associated scripting language built on the .NET Framework. PowerShell provides full access to the Component Object Model (COM) and Windows Management Instrumentation (WMI), enabling administrators to perform administrative tasks on both local and remote Windows systems as well as WS-Management and Common Information Model (CIM) enabling management of remote Linux systems and network devices.

Share tech news, updates, or what's on your mind.

Sign up to Post

I'm looking for a way to improve this powershell script:

Get-Mailbox -ResultSize Unlimited -OrganizationalUnit "OU=TestOU,DC=DOMAIN,DC=COM" |Select-Object DisplayName,PrimarySmtpAddress, @{Name="EmailAddresses";Expression={$_.EmailAddresses |Where-Object {$_.PrefixString -ceq "smtp"}| ForEach-Object {$_.SmtpAddress}}} |Export-CSV c:\csv_exports\exportsmtp3.csv -NoTypeInformation

Open in new window


This script woks for the most part, but all the secondary smtp addresses are contained in the same block in the exported csv. What I need is to either have all the smtp addresses in their own values, or to filter and only export a specific "@domainname.com" addresses and not the rest.

This is on the Windows Server 2008 r2 with Exchange 2010

Thank you,

-Matt
0
Has Powershell sent you back into the Stone Age?
LVL 6
Has Powershell sent you back into the Stone Age?

If managing Active Directory using Windows Powershell® is making you feel like you stepped back in time, you are not alone.  For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why.

I have a GMSA account that's starting a service
The service code is in powershell

Looking to authenticate to sql server but seems to fail to login
GMSA account is dbo of the database

Should this work?

A standard windows service account works fine


$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
	$SqlConnection.ConnectionString = "Server = $sqlServer; Database = $SQLDBName; Integrated Security = True;"
	$Command = New-Object System.Data.SqlClient.SqlCommand
	$Command.CommandTimeout = 0
	$Command.Connection = $SqlConnection

Open in new window

0
how do I remove files and folders from multiple client machines using sccm 2016? do I use application or package?
I am looking to delete certain .exe files and some folders from few location on client machines.

what script should I use? do I use powershell or vbscript? and what is the installation command line for using either one?

Regards

AZ
0
Having issues with the script, seems to be failing with the email code.  The objective is to send managers a list of their consultants who have expired user accounts in AD.

We based this from the example ps script from the link in the first comment.

# https://social.technet.microsoft.com/Forums/windowsserver/en-US/9d080c24-b2a2-4d9b-b50b-ca7fb9d95a91/account-expiration-email-notification?forum=winserverpowershell
# Find all managers and check each manager's employees for expired accounts in Consultants OU

Import-Module ActiveDirectory 

$style = "<style>BODY{font-family: Arial; font-size: 10pt;}"
$style = $style + "TABLE{border: 1px solid black; border-collapse: collapse;}"
$style = $style + "TH{border: 1px solid black; background: #dddddd; padding: 5px; }"
$style = $style + "TD{border: 1px solid black; padding: 5px; }"
$style = $style + "</style>"

Get-ADUser -Filter * -Properties directReports,EmailAddress -SearchBase "OU=Consultants,OU=User Accounts,DC=Microsoft,DC=com" | ForEach {

    $body = @()
    
    If ($_.directReports) {

        $managerEmailAddress = $_.EmailAddress

        $_.directReports | ForEach {

            $userDetails = Get-ADUser $_ -Properties AccountExpirationDate

            If ( $userDetails.AccountExpirationDate ) {

                If ( [datetime]($userDetails.AccountExpirationDate) -lt (Get-Date) ) {

                    $sendEmail = $true

                    
                    $body += New-Object PsObject -Property @{
      

Open in new window

1
Good morning,

$Computers = Get-ADComputer -Filter * -searchbase "OU=branch,DC=net,DC=Company,DC=co,DC=uk" | Where-Object {$_.Name -like "*TM*"} | Select -Property Name

ForEach ($Computer in $Computers) {
	If (Test-Connection -ComputerName $Computer -Quiet) {
		& shutdown.exe -m "\\$($Computer)" /f /R
	} Else {
		"$($Computer) is not online" | Out-File -Append "C:\Powershell Projects\reboot script\computersnotonline.txt"
	}
}

Open in new window


Right, so this works fine, it enumerates the machines with the correct names from the specified OU.

How can I make it limit the reboot to 20 and wait 20 seconds until each machine is back up?

Thanks

Alex
0
I have an excel file with 2 sheets and need to convert into html and send an email using sendemail using PowerShell. I would like to send html file as an embedded email rather than attachment. I want entire script in PowerShell

Any help is appreciated.

Suresh
0
I picked up this command from EE which gives a head count per security group. Does anyone know if the following command will also factor in its count, “group members within sub groups”? Or will it only enumerate the first level of sub groups and their members? or does it keep going as far down the hierarchy as necessary.

Get-ADGroupMember -Identity <Group> -Recursive | Measure-Object | Select-Object -ExpandProperty Count


Does anyone know how it could be changed to not only give the count (of total members including sub groups), but also give the details of all members as well (including the sub groups)?
1
I am sharing with you some quick commands on using Office 365 Power Shell that i have collected from different Microsoft articles and blogs pages to perform Office 365 admin center tasks from the command line to your Office 365 organization:
0
I am sharing with you some quick commands on using Office 365 Power Shell to perform Office 365 admin center tasks from the command line to your Office 365 organization:

How you can Connect to Office 365:

Import Office 365 Module  : Import-Module MSOnline
Connect to your Directory  : Connect-MsolService
Users Commands:

List all users:                        get-msoluser -all
List all users with count:        get-msoluser -all | measure

Change UPN on all unlicensed users:      Get-MsolUser -all | Where { -Not $_.UserPrincipalName.ToLower().StartsWith(“admin@”) } | ForEach { Set-MsolUserPrincipalName -ObjectId $_.ObjectId -NewUserPrincipalName ($_.UserPrincipalName.Split(“@”)[0] + “@acig.com.sa”) }
Remove all unlicensed users:       Get-MsolUser -all | Where-Object {$_.isLicensed -ne "true"} | Remove-MsolUser -Force


Office 365 Licensing Information:

You can use a Power Shell script to check if users have a license assigned directly or inherited from a group:

      1. Run the connect-msolservice cmdlet to authenticate and connect to your tenant as explained on the above commands.
      2. Get-MsolAccountSku can be used to discover all provisioned product licenses in the tenant.

Thanks and hope this might helps.

      
      

1
Whenever I type text in the powershell window it is yellow.  I have tried adjusting the colors in properties, but it still comes out yellow.  How do I change it to white?
0
What does it mean to be "Always On"?
LVL 4
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Hi.

I have a text file with a list (more than 10 and growing) of hostnames on a domain.

I need a script to ping each of the hostnames, perform a -arp ping, and perform a last logged on check with time with the results output to CSV.

I have a Powershell Script that does a ping test from a text file. How do I perform all of the above in one and output the results to CSV as a report?

$names = Get-content "hnames.txt"

foreach ($name in $names){
  if (Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue){
    Write-Host "$name,up"
  }
  else{
    Write-Host "$name,down"
  }
}

Open in new window

0
Hi,

We have an organogram which is searchable (web based, don't know what  is running below). I'd like to search through it via Powershell then showing me the result.
F.e. John Doe gives a result in the webpage http://ourcompany/organogram (when entering a search box)
I'd like to have get-organogram -user 'John Doe'. Searched source code for this page but did not found enter or 'first name' ...


How could I achieve this?
J.
0
I have been using powershell to service workstation on our network.  The other day I figured I would try some new thing so I was playing with the new-pssession command.  The first time I tried it the session froze.  I could not connect to anything to check or correct errors. Dummy me I started to look up fixes but I made it worse.  Now I think I may have changed the whole networks powershell to use https.  I am now getting permission errors.  Is there a way to reset powershell defaults? Can I make an accross the board change to correct the network problem?
0
Need to run a Powershell script on AD that will extract all  users that have not logged in past over 120 days. I need to get when the account was created , the last time they logged in if any and the number of days past 120 days ., then export this into a csv file
0
Hello Experts,

I have the following PowerShell Script that I found online to remove Windows 10 Apps from Enterprise. The Script does not seem to run properly. When I run it will not remove some of the Apps. The error message for the Apps that it does not remove is "Unable to find provisioned package"

Below is the Script:
($AppsList = "Microsoft.Office.Sway","Microsoft.RemoteDesktop","Microsoft.MicrosoftPowerBIForWindows","Microsoft.NetworkSpeedTest","46928bounde.EclipseManager","D5EA27B7.Duolingo-LearnLanguagesforFree","AdobeSystemsIncorporated.AdobePhotoshopExpress","Microsoft.Getstarted","Microsoft.Messaging","Microsoft.BingWeather","Microsoft.BingNews","Microsoft.3DBuilder","Microsoft.Microsoft3DViewer","Microsoft.MicrosoftOfficeHub","Microsoft.MicrosoftSolitaireCollection","Microsoft.Office.OneNote","Microsoft.OneConnect","Microsoft.People","Microsoft.WindowsFeedbackHub","Microsoft.WindowsMaps","Microsoft.XboxApp","Microsoft.ZuneVideo","Microsoft.ZuneMusic","Microsoft.SkypeApp","Microsoft.WindowsAlarms","microsoft.windowscommunicationsapps","Microsoft.Windows.Photos","ActiproSoftwareLLC.562882FEEB491","PandoraMediaInc.29680B314EFC2","Microsoft.WindowsStore")

ForEach ($App in $AppsList)
{
$PackageFullName = (Get-AppxPackage $App).PackageFullName
$ProPackageFullName = (Get-AppxProvisionedPackage -online | where {$_.Displayname -eq $App}).PackageName
write-host $PackageFullName
Write-Host $ProPackageFullName
if ($PackageFullName)
{
Write-Host 

Open in new window

0
I need help with the middle portion of this script...

"""foreach ($Man in $managerusers2)
    {
    $managerusers = $managerusers + Get-ADUser $Man -Properties * | Select-Object samaccountname, mail
    }"""

I have a group called "Test_Department_Manager" and in the group I have a few managers. I need to send an email to them that list each employee that they are a direct report for and who has access to their employees mailbox..
Import-module activedirectory
Import-Module MSOnline

$Username = "user@domain.com"
$Password = ConvertTo-SecureString Password97 -AsPlainText -Force

$LiveCred = New-Object System.Management.Automation.PSCredential $Username, $Password
$senderemail="user@domain.com"
$subject="Your Direct Reports and Permission"

$managerusers2=Get-ADGroupMember -identity "Test_Department_Manager"



foreach ($Man in $managerusers2)
    {
    $managerusers = $managerusers + Get-ADUser $Man -Properties * | Select-Object samaccountname, mail
    }




Foreach ($manager in $managerusers)
 {
	# Find all direct user reporting to manager	
	
	$directreportusers=Get-ADUser -Identity test_director -Properties directreports | Select-Object -ExpandProperty directreports |  Get-ADUser -Properties mail |  Select-Object SamAccountName, mail
	
	#$directreportusers=Get-ADDirectReports -Identity $manager.SamAccountName
	
	$manageremail=$manager.mail
	
	Foreach ($user in $directreportusers)
		{
		
		$Session = New-PSSession -ConfigurationName Microsoft.Exchange 

Open in new window

0
Since installing Office 2013 in our environment, we have to manually turn off a Windows system setting, 'Animate controls and elements inside windows' due to performance issues.

System >> Advanced System Settings >> Advanced >> Performance, Settings >> under Custom, 'Animate controls and elements inside windows' check box.

Has anyone done this via batch / GPO / or any other mass method successfully?

This is for Win 7 SP1 Enterprise.
0
Hi Guys,

when assigning a license out of an accountsku to a user, you can limit the given functionality with -disabledPlans.
Is there a way to turn the logic upside down and work with "EnabledPlans" ?

Thank you for helping out,

Grtz
0
Hi Experts

Am having a small issue with PowerShell when using a DatagridView in Windows Forms.

The DatagridView is being added to the form, but when the form is shown for the first time, it is "blank".  Or better said, the DatagridView is a White box.

Here is the code I use:

Add-Type -AssemblyName System.Windows.Forms

$objFrm = New-Object System.Windows.Forms.Form
$dgv_Info = New-Object System.Windows.Forms.DataGridView

$objFrm.Size = New-Object System.Drawing.Size(722, 563)
$objFrm.MinimumSize = New-Object System.Drawing.Size(722, 563)

$dgv_Info.Location = New-Object System.Drawing.Point(13, 342)
$dgv_Info.Size = New-Object System.Drawing.Point(681, 145)
$dgv_Info.Anchor = $AnchorStyle_BottomLeftRight
$dgv_Info.ColumnHeadersVisible = $true
$dgv_Info.RowHeadersVisible = $true
$dgv_cbCellSQLInst = New-Object System.Windows.Forms.DataGridViewComboBoxCell
$dgv_cbCellSQLInst.DataSource = $SQLInstanceNumbers
$outvar = $dgv_Info.Columns.Add($dgv_cbCellSQLInst)
$dgv_Info.Columns[0].Name = "Header 1"
$dgv_Info.Columns[0].AutoSizeMode = 'Fill'
$dgv_Info.Sort($dgv_Info.Columns[0], [System.ComponentModel.ListSortDirection]::Ascending)
$dgv_cbCellDrv = New-Object System.Windows.Forms.DataGridViewComboBoxCell
$dgv_cbCellDrv.DataSource = $DrvLetters
$outvar = $dgv_Info.Columns.Add($dgv_cbCellDrv)
$dgv_Info.Columns[1].Name = "Header 2"
$dgv_Info.Columns[1].AutoSizeMode = 'Fill'
$dgv_DBDisk = New-Object System.Windows.Forms.DataGridViewTextBoxCell
$outvar = 

Open in new window

0
Visualize your virtual and backup environments
LVL 1
Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

Hi, I wonder if someone could help

Need run a report that identifies users that have expired passwords in AZURE AD and have licenses for apps assigned

Thanks in Advance

John
0
Hi,

We have an internal url at work where I can navigate to using chrome and view the pdf and download without any issue. When I try to do the same thing in powershell using code like below I get an unauthorised error. I don't understand the security part to well so trying to work out why I'm blocked through powershell but not through chrome. Do I need to send my credentials through some way? or do something else so powershell uses the same settings as the browser

$Url = "https://server/file.pdf"
$Path = "c:\temp\file.pdf"
[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
$webClient = new-object System.Net.WebClient
$webClient.DownloadFile( $Url, $Path )
0
exchange 2010 export mailbox to pst PowerShell
The Exchange 2010 Export Mailbox to PST Powershell. The steps also explain various things like what all parameters in exchange PowerShell are required by a user and what is not?
0
Hello,

I have a powershell script which essentially "works" but with one caveat.

This script queues all the mailboxes to export immediately (i.e. if my text file contains a list of 15 mailboxes then the script queues all 15 mailboxes to export immediately).

The problem I have found is that when the server is trying to export more than one mailbox concurrently, some of the mailbox exports fail.

So I would like a way to either:

1. Modify the script to only perform one export at a time or
2. Configure some setting in Exchange so that only one New-MailboxExportRequest is executed at a time (I've had a look at the settings for this cmdlet and cannot see an option to do this)

$Export = Get-Content C:\Mailboxes.txt
foreach ($i in ($Export)) {New-MailboxExportRequest -ContentFilter {(Received -lt '01/09/2017')} -BadItemLimit 200 -AcceptLargeDataLoss -Mailbox $i -Filepath "\\SERVER\Mail\$($i).pst" }

Open in new window


Thank you
0
I find that a old exchange server is left in exchange organization. I guess this was left in previous migration from the si company. Is it possible to remove it ? The old Exchange physical server is no longer exist in our network.


Get-ExchangeServer | Format-List Name, Edition, AdminDisplayVersion, site,serverrole


Name                : SERVER01
Edition             : Enterprise
AdminDisplayVersion : Version 6.5 (Build 7638.2: Service Pack 2)
Site                :
ServerRole          : None

Name                : MAIL1
Edition             : Standard
AdminDisplayVersion : Version 14.3 (Build 123.4)
Site                : abc.com/Configuration/Sites/DataCentre
ServerRole          : ClientAccess, HubTransport

Name                : MAIL2
Edition             : Enterprise
AdminDisplayVersion : Version 14.3 (Build 123.4)
Site                : abc.com/Configuration/Sites/DataCentre
ServerRole          : Mailbox
0
Hello EE,

I am looking for some help with a powershell script or template to help me get started.
I have 5 machines named test1, test2....test5 where I need to copy a file from a network share g:\copy
to each of these machines startup folder.

Any help would be great.  This can't be just manual.
0

Powershell

15K

Solutions

7K

Contributors

Windows PowerShell is a task automation and configuration management framework from Microsoft, consisting of a command-line shell and associated scripting language built on the .NET Framework. PowerShell provides full access to the Component Object Model (COM) and Windows Management Instrumentation (WMI), enabling administrators to perform administrative tasks on both local and remote Windows systems as well as WS-Management and Common Information Model (CIM) enabling management of remote Linux systems and network devices.