Quantcast
Channel: PowerShell General
Viewing all 10624 articles
Browse latest View live

Trying to get a list of users without an X500 address

$
0
0

Hi

I am trying to get a list of users who do not have an X500 address. All the users have an SMTP address, but need an X500 address in order for them to appear as contacts in another domain in another forest using the galsync method.

I managed to find a script which will display users with an SMTP address, and this seems to work. Same with displaying users with an X500 address. When I try to modify it so that it only displays users without an X500 address, it either displays nothing or it moans about the command I used.

Here is the script:

Get-Mailbox | Select-Object DisplayName,UserPrincipalName,@{Name="EmailAddresses";Expression={$_.EmailAddresses |Where-Object {$_ !(-LIKE) "SMTP:*"}}} | Sort | Export-Csv "C:\Users\$env:username\Desktop\test.csv"

Could someone help? I am not an expert in scripting, but I am learning. Slowly.

Any help will be gratefully received.

Anthony


returning a value from a drop-down

$
0
0

Hello,

I'm writing a script to create new users through a form (the normal user creation process is long and complex and therefore prone to human error), but I'm having issues capturing values from a drop-down.

Here is my code.... (sorry couldn't see how to insert it as a block of code!)

########################

# Edit This item to change the DropDown Values

[array]$DropDownArray = "John", "Peter", "Paul"

# This Function Returns the Selected Value and Closes the Form

function Return-DropDown {

 $Choice = $DropDown.SelectedItem.ToString()
 $Form.Close()
 Write-Host $Choice

}

[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")


$Form = New-Object System.Windows.Forms.Form

$Form.width = 300
$Form.height = 150
$Form.Text = ”DropDown”

$DropDown = new-object System.Windows.Forms.ComboBox
$DropDown.Location = new-object System.Drawing.Size(100,10)
$DropDown.Size = new-object System.Drawing.Size(130,30)

ForEach ($Item in $DropDownArray) {
 $DropDown.Items.Add($Item)
}

$Form.Controls.Add($DropDown)

$DropDownLabel = new-object System.Windows.Forms.Label
$DropDownLabel.Location = new-object System.Drawing.Size(10,10)
$DropDownLabel.size = new-object System.Drawing.Size(100,20)
$DropDownLabel.Text = "Items"
$Form.Controls.Add($DropDownLabel)

$Button = new-object System.Windows.Forms.Button
$Button.Location = new-object System.Drawing.Size(100,50)
$Button.Size = new-object System.Drawing.Size(100,20)
$Button.Text = "Select an Item"
$Button.Add_Click({Return-DropDown})
$form.Controls.Add($Button)

$Form.Add_Shown({$Form.Activate()})
$Form.ShowDialog()

$FirstName = $Choice
$LastName = "Test"
$Name = $FirstName + " " + $LastName
#Get First Initial from Firstname.
#From position 0 select the first 1 character
$FirstInitial = $FirstName.Substring(0,1)
$Alias = $FirstInitial + $LastName
$Email = $Alias + "@daslaw.co.uk"

New-Mailbox -UserPrincipalName $Email -Alias $Alias -Database "NonTeam" -Name $Name -OrganizationalUnit "Test Team" -Firstname $FirstName -LastName $LastName -DisplayName $Name -ResetPasswordOnNextLogon $true

########################

I've cut the code back to try and locate the error and it seems as though the data is being written to the variable ($Choice) as it appears in the host screen using "Write-Host $Choice" but it looks as though it is being cleared after.

 

Script to show failed databases and send an email

$
0
0

Normal 0 false false false EN-GB X-NONE X-NONE MicrosoftInternetExplorer4

Hi

I usually check all the databases in the DAG to make sure there are none that have failed or suspended. The command i use is crude but works and displays the name e.g

db1\server1  failed suspended

db5\server4  suspended

db17\server6 failed

get-mailboxserver |Get-MailboxDatabaseCopyStatus |? {$_.status -ne"healthy"} |? {$_.status -ne "mounted"} | Sort-Object databasename

 

I wanted to just automate this and sent an emailing  me a list of all failed databases name/server and if there are no failed databases to tell me there are none.

Being a total novice i tried this and failed any help would be really great

 

$servers=get-mailboxserver

$dbcopystatus=$servers|Get-MailboxDatabaseCopyStatus

$nothealthy=$dbcopystatus|? {$_.status -ne"healthy"}

$nomounted=$nothealthy|? {$_.status -n e "mounted"}

$faulty=$nomounted| Sort-Object databasename

$output = If (@($faulty).count > 0)

    { Write-output “Failed disk $faulty"`n"}

    Else

    {  Write-output“No Disks are faulty”  `n"    }

 

Send-MailMessage -from "Exchange2010@abc.com" -to "admin@xyz.com" -Subject "bad db disk $((get-date).ToShortDateString())" -body $output -bodyashtml -SmtpServer"SMTP" -Priority high

 

Thanks

ian

Powershell to check the domains in the proxy address

$
0
0

Hello Guys,

I am looking for a script that will comapare a file of domains to all the proxy address list of the users in AD and let me know if any users has an additional domain proxy address.

Also powershell script to have output of the on-prem GAL to a CSV file.

 

Any suggestion is appreciated.

Thanks & Regards,

AB

 

 

 

 

 

 

parallel port GPI and GPO

$
0
0

I'm sitting in front of a Dell Precision T5500 running Windows 7 Professional, 64bit.  It has a parallel port, (device manager describes it as "ECP Printer port LPT1"), with a driver provided by Microsoft, (c:\windows\system32\DRIVERS\parport.sys).  If I were to connect some dip switches and pull-up resistors to the data lines of the parallel port, can someone show me a sample powershell script that would read those switches--the byte established by those switches, and create a variable?  And If I were to connect some LEDs to the data lines of that port, can someone show me a sample powershell script that could send a byte to illuminate them?

Script to rename files

$
0
0

Hi I need a powershell script that renames a lot of .ftp files to .txt. Thanks

Can I use IExpress to pacakge a Batch file which calls a PS script ?

$
0
0

I used to package Batch file using IExpress.
The reason for this was that my co-worker would change my code, then complain that the
batch file not longer worked.  So packaging it into a nice EXE would prevent modification

Now that I'm starting to use PowerShell more and more I would like to share my scripts with my team
(I now work in a new company).  Since this place does not have any tools I used PS to create some.


I have a PS script which I can execute either by the console or calling it from a BatchFile.

I can package the batch file and PS script, however, when executed the screen comes up and goes away quick

I"ve tried other script with the same results

What am I doing wrong?

 

Thank you

 This is what I use in my batch file

PowerShell -NoProfile-ExecutionPolicy Bypass -Command"& '.\Get-RemoteInstalledApps.s1'"

This is a script which I call from my batch file

# Prompt Tech for the Hostname of the PC
$Workstation=Read-Host"Computer Name"

# NOTE: RemoteRegistry Service needs to run on a target system!
$Hive='LocalMachine'

# you can specify as many keys as you want as long as they are all in the same hive
$Key='SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall', 'SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall'
# you can specify as many value names as you want

$Value='DisplayName', 'DisplayVersion', 'Publisher', 'UninstallString'

# Enter computer name ensure you have access to the remote system adn remote registry is enabled
$ComputerName=$env:Workstation

# add the value "RegPath" which will contain the actual Registry path the value came from (since you can specify more than one
key)
$Value= @($Value) +'RegPath'

# now for each regkey you specified...
$Key | ForEach-Object {
# ...open the hive on the appropriate machine
$RegHive= [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($Hive, $Workstation)

# ...open the key in that hive...
$RegKey=$RegHive.OpenSubKey($_)

# ...find names of all subkeys...
$RegKey.GetSubKeyNames() | ForEach-Object {
# ...open subkeys...
$SubKey=$RegKey.OpenSubKey($_)
# ...and read all the requested values from each subkey
# ...to store them, use Select-Object to create a simple new object
$returnValue= 1 | Select-Object-Property$Value

$Value
| ForEach-Object {
$returnValue.$_=$subkey.GetValue($_)
}

# ...add the current regkey path name
$returnValue.RegPath=$SubKey.Name

# return the values:
$returnValue

# close the subkey
$SubKey.Close()
}

# close the regkey
$RegKey.Close()
# close the hive
$RegHive.Close()

} | Out-GridView

Write-Host
"Press any key to continue ..."
$x=$host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

Pipeline Variables

$
0
0

 

How do we assign the current value of one pipeline variable to another?

This works fine for me.

$hash = ((get-content .\hash.txt) -join "`n") | ConvertFrom-StringData

$hash.GetEnumerator() | % { 

$_.value 

}

Now how do I assign each value from the hash table to $_.UserPrincipalName in the following?

$hash = ((get-content .\hash.txt) -join "`n") | ConvertFrom-StringData

$MaxPassAge = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge.days

$DaysToExpire = 25

$hash.GetEnumerator() | % { 

Get-ADUser -SearchBase (Get-ADRootDSE).defaultNamingContext -Filter {(Enabled -eq "True") -and (PasswordNeverExpires -eq "False") } -Properties PasswordLastSet | Select-Object givenname,SamAccountName,UserPrincipalName,@{Name="Expires";Expression={$MaxPassAge -((Get-Date) - ($_.PasswordLastSet)).days}} | Where-Object { $_.UserPrincipalName -eq $_.value } | Where-Object {$_.expires -gt 0 -AND $_.expires -le $DaysToExpire }

}

Any pointers are highly appreciated. Thanks

 


Form parameters

$
0
0

Hi,

I build a form with those parameters:

 

$form.Height=400

$form.Width=380

$form.Text="Box"

$form.FormBorderStyle=1

 

I know that there is a parameter that can open it on the center : $Form.StartPosition = "CenterScreen"

I need that the form will open on the right center of the screen.

 

Thanks

Lior 

 

 

Delete multiple files from reference file

$
0
0

Hello,

 

I would like to know the command to delete some files from  a particular directory. I have set of files which ends with .xml extension. I made a list of files to be deleted and saved it in a another reference file called tobedelete.txt.

How do I call PowerShell to delete the files that are listed in the file "tobedeleted.txt"

 

Please advise.

 

 

 

 

Merge Multiple .TXT files

$
0
0

Hello,

I need to merge multiple .txt files into one txt file. Can someone help with a powershell script for that? Also will it be possible to cut off the headers in each of the files and just have one? For example

File1.txt

© 2014 by Heathrow Capital, Inc.
HCMarketData 1234569 2233 FINAL    
G CCAVD 20141 9.4215
G FROOK 20141 9.8248
G RSVVP 20141 6.0302

File2.txt

© 2014 by Heathrow Capital, Inc.
HCMarketData 1234569 2233 FINAL    
R HHHH 20141 9.4215
R HHDG 20141 9.8248
R GGHD 20141 6.0302

Thanks,

 

richtextbox question

$
0
0

HI
when i am trying to copy from excel to the richtexbox. It is copying the tables also.
i just want it to get copied as the plain text.

Thanks

 

 

 

Getting MobileDeviceStats From O365

$
0
0

Hello,

I have a script that I have created to pull a list of all the Mobile devices and their statistics from our Office 365 environment.  When I execute this script manually, it completes without error and my report is generated.  When I create a scheduled job to run the script, it hangs at connecting to the MSOLservice.  I opened a ticket with O365 support and they reported that since it is a custom script they are unable to assist.  Have any of you ran into this type of issue with O365?  Are you able to run scheduled jobs to pull data on a regular basis?

Thanks in advance, here is the script.

 

<#
.Synopsis
Generates list of all MobileDeviceStats for devices in Office 365.

.DESCRIPTION
Generates list of all MobileDeviceStats for devices in Office 365.

.EXAMPLE
.\Get-MobileDeviceStats_v4.ps1

.NOTES
This script utilizes the ActiveDirectory PowerShell module, which must be available on the launching system.
This can be obtained from the Remote Server Administration Tools (RSAT) by Microsoft.
A RSAT for Windows 8 can be obtained here: http://www.microsoft.com/en-us/download/details.aspx?id=28972
#>

Import-Module MSOnlineExtended
Write-EventLog-LogName Application -Source'MobileDeviceStats Script'-EntryType'Information'-EventId 1 -Message'The PowerShell script, Get-MobileDeviceStats.PS1, has started.'
#STORED CREDENTIAL CODE
$AdminName="admin@domain.onmicrosoft.com"
$CredsFile="C:\ps\MobileDeviceStats\$AdminName-PowershellCreds.txt"
$FileExists=Test-Path$CredsFile
if ($FileExists-eq$false) {
Write-Host'Credential file not found. Enter your password:'-ForegroundColor'Yellow'
Read-Host-AsSecureString | ConvertFrom-SecureString | Out-File$CredsFile
$password=Get-Content$CredsFile | ConvertTo-SecureString
$Cred=New-Object-TypeNameSystem.Management.Automation.PSCredential-Argumentlist$AdminName,$password}
else
{Write-Host'Using your stored credential file'-ForegroundColor'Green'
$password=Get-Content$CredsFile | ConvertTo-SecureString
$Cred=New-Object-TypeNameSystem.Management.Automation.PSCredential-ArgumentList$AdminName,$password}

#Create remote session for O365 and Azure AD
$Session=New-PSSession-ConfigurationNameMicrosoft.Exchange-ConnectionUri https://ps.outlook.com/powershell/-Credential$Cred-Authentication'Basic'-AllowRedirection
Import-PSSession$Session
Import-Module MSOnline
Connect-MsolService-Credential$Cred

Write-EventLog-LogName Application -Source'MobileDeviceStats Script'-EntryType'Information'-EventId 2 -Message'The PowerShell script, Get-MobileDeviceStats.PS1, has initiated the remote session.'

#Set variables
$ExportedFilePath1="C:\ps\MobileDeviceStats\Reports\MobileDeviceStatistics_$((Get-Date).ToString('MM-dd-yyyy')).csv"
$Script:ExportedFile=$ExportedFilePath1

Write-EventLog-LogName Application -Source'MobileDeviceStats Script'-EntryType'Information'-EventId 3 -Message'The PowerShell script, Get-MobileDeviceStats.PS1, has successfully set the variables'

#Send email function
function sendmail
{
Send-MailMessage-To"user@domain.com" `
-From"PowerShell@domain.com" `
-Subject"Mobile Device Statistics" `
-Priority'Normal' `
-Attachments$Script:ExportedFile `
-Body"The attached CSV file contains the current list of Mobile Devices and their corresponding statistics.

Best Regards,
PowerShell

" `
-SmtpServersmtp.domain.com
}
#Send email update function
function sendupdate
{
Send-MailMessage-To"User2@domain.com" `
-From"PowerShell@domain.com" `
-Subject"Mobile Device Statistics" `
-Priority'Normal' `
-Body"The Get-MobileDeviceStats script has successfully completed and all remote sessions have been cleared.

Best Regards,
Your Friendly PowerShell Nerd

" `
-SmtpServersmtp.domain.com
}

Write-EventLog-LogName Application -Source'MobileDeviceStats Script'-EntryType'Information'-EventId 4 -Message'The PowerShell script, Get-MobileDeviceStats.PS1, is beginning the data gathering process.'
#
#Add sleep http://support2.microsoft.com/kb/2881759
#
$MB=Get-MobileDevice-Resultsize unlimited
$MB | foreach {Get-MobileDeviceStatistics$_.identity; Start-Sleep-Milliseconds 2000} | Select-Object FirstSyncTime,LastPolicyUpdateTime,LastSyncAttemptTime,LastSuccessSync,DeviceType,DeviceID,DeviceModel,DeviceFriendlyName,DeviceOS,DeviceOSLanguage,Identity,DeviceAccessState,NumberOfFoldersSynced |
Export-Csv-NoTypeInformation$Script:ExportedFile

Write-EventLog-LogName Application -Source'MobileDeviceStats Script'-EntryType'Information'-EventId 5 -Message'The PowerShell script, Get-MobileDeviceStats.PS1, has completed the data gathering process.'

sendmail
Get-PSSession | Remove-PSSession
sendupdate
Write-EventLog-LogName Application -Source'MobileDeviceStats Script'-EntryType'Information'-EventId 6 -Message'The PowerShell script, Get-MobileDeviceStats.PS1, has completed.'

Particular String Bold in rich text box

$
0
0

$outputBox = New-Object System.Windows.Forms.RichTextBox
$outputBox.Location = New-Object System.Drawing.Size(10,250)
$outputBox.Size = New-Object System.Drawing.Size(1160,590)
$outputBox.MultiLine = $True
$outputbox.font = "lucida console,9"
$outputBox.ScrollBars = "Vertical"
$outputbox.readonly = $true

I have an output box [richtextbox]. I have function that will display data into that. Is there any way we can have the selected string/word in bold ?

 

check the admin$ of a machine?

$
0
0

I have a list of machines that I can ping but when I try to connect to them I can't.   I will open up Explorer and enter \\machinename\c$  or \\machinename\admin$  and it can't connect, yet I can ping them.

Using PowerShell can you mimic doing a \\machinename\admin$ ?  Yes, I can script it so it runs this from a command line, this is not want I want.  I want to know if there is a Powershell command to check the Admin$ or C$ on a remote machine?

 

 


Looping Problems

$
0
0

$NoPing = "Can't Ping Machine"
$erroractionpreference = “SilentlyContinue”
$a = New-Object -comobject Excel.Application
$a.visible = $True
$b = $a.Workbooks.Add()
$c = $b.Worksheets.Item(1)
$c.Cells.Item(1,1) = “Computer Name”
$c.Cells.Item(1,2) = “Computer OS Version”
$c.Cells.Item(1,3) = “Admin$”
$c.Cells.Item(1,4) = “Description”
$d = $c.UsedRange
$d.Interior.ColorIndex = 37 
$d.Font.ColorIndex = 1     
$d.Font.Bold = $True
$d.EntireColumn.AutoFit()
$intRow = 2
$NoPing = "Can't Ping Machine"

$machine = get-content 'c:\temp\tmp\ping\CMPing.txt'
foreach ($pc in $machine) {$getip = ((Test-Connection $pc -Count 1));
    if ($getip -like '*Source*')   {
           
     $computerOS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $pc | Select-Object -     ExpandProperty version;
            $admindollar = "Admin$ Reachable"
            $desc = (Get-ADComputer $pc -Properties Description).description
     $c.Cells.Item($intRow, 1) = $pc
            $c.Cells.Item($intRow, 2) = $computerOS
            $c.Cells.Item($intRow, 4) = $desc
            $intRow += 1
            $d.EntireColumn.AutoFit()  }

    Else {
        $c.Cells.Item($intRow, 1) = $pc;
        $c.Cells.Item($intRow, 4).Interior.ColorIndex = 6
        $c.Cells.Item($intRow, 4).Font.ColorIndex = 1  
        $c.Cells.Item($intRow, 4) = $NoPing
    }}

I have more code than this but this is the meat of the script.  Before this runs I have some code that opens Excel and creates the headers.

Here is my problem.   If the machine cannot be pinged then the ELSE should run and does.  The value for $NoPing is entered into cell .d but then 1 second later it is overwritten with the value from $desc.   I was watching this as it happened.   I see "Can't Ping Machine" and then 1 second later it is overwritten with the Description data from AD.

how come? 

 

How to get web page information?

HTML Body Extraction

$
0
0

Hi All,

Ok... so I got Powershell Studio for Christmas (cause I'm a sad geek lol) and I'm loving it. I wrote a program in it using powershell and .net. After fuzzing the stuffing out of it last night, I found an issue. Like a good boy I went to bed and promised to look into the problem today.

Today I awoke early, grabbed some tea and got stuck in...

...and nearly 12 hours later I'm still at it. I think I've googled the google out of google and I can't find an answer. I've tried regXing, I've tried splitting, I've tried offering my computer money.... I won't go on. Needless to say, I've had one of those days. I'm about to head off to bed. Today was my last day off, my brain aches and I have work in the morning!

Before I hit the sack and spend the first hour wondering what went wrong or even worse keeping myself awake by coding in my head (you've all done it too!), I thought I'd post up my problem. Hopefully some of you great guys n girls will leave me a few xmas gifts in the form of resolutions to my problem. So let me explain:

I wrote a program that does stuff. One of it's features is that in response to a given scenario it will pick up an html document on a hard drive and email it to me or another admin. The problem is, some email clients won't display the html email properly (including mine - stupid hotmail). I found a way around this by stripping all but the Body of the document out and then targetting the document. Now I want powershell to do this for me. Hey lets get even simpler... since any html document only has one body, I want powershell to look at any html document I point it towards and import the body, including the body tags.

I thought this would be simple, and probably is for you guys... but the issue has drained me!

Over to you! 

Many thanks and Merry Christmas!

I need to create a script to install an executable on multiple remote 64 bit windows systems using PS

$
0
0

([WMICLASS]"\\$RemoteSystem\ROOT\CIMV2:win64_process").Create("cmd.exe /c C:/InstallSetup/Program.exe /s /v`" /qn")

write-host "Successfully installed" 

But even running this on a single system gives error

Where RemoteSystems =nyplab01 to nyplab10 ( 10 computer systems)

Path of the executable will be on my local desktop C Drive (C:/InstallSetup/Program.exe).

I also need to provide credentials for the admin for all windows.

there could be times where these is error incase the admin password changed by user then i need to display error because of this or maybe the system is 32 bit.

Now i am not sure of  installing this over the network would be good idea or first copy the executable and then run it locally on the remote computers.

Create line break in string/message

$
0
0

Hi guys, I'm using powershell to send an email which works fine, however I'd like to reformat the body a little.

I have a number of PC names in the array which I then join.

 

$merge = $PCs_in_array -join ", "

$body = @"

"Hello, these are the PCs in the list:"

$merge

"You will receive another email in 2hrs"

"@

 

The email looks like this at the moment:

Hello, these are the PCs in the list:

PC1, PC2, PC3, PC4

You will receive another email in 2hrs

 

What I'd like it look like:

Hello, these are the PCs in the list:

PC1

PC2

PC3

PC4

You will receive another email in 2hrs

 

How do I create that line break for each PC?

Viewing all 10624 articles
Browse latest View live