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

Strange: "Program 'more.com' failed to run: Object reference not set to an instance of an object"

$
0
0

All,

  The only changes I've made to my W2K12R2 servers is i added some code to my PSH Profile to center my screen and set size/width/font properties.  I also applied the latest round of MS Patches a few weeks back.  I'm trying to use the HELP function of PSH and as you can see below this is the output I get.  Get-Help works, but I need to paginate the output (it's just the way I roll) but the function HELP has hiccuped and I'm stumped.  I do NOT have this problem with my W2K8R2 boxes at all.  All Servers are running PSH 4.0.  Any ideas, thoughts as to what I've run into?

PS C:\Windows\system32> help get-command -Examples
Program 'more.com' failed to run: Object reference not set to an instance of an object.At line:14 char:14
+     $input | more.com
+              ~~~~~~~~.
At line:14 char:5
+     $input | more.com
+     ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (:) [], ApplicationFailedException
    + FullyQualifiedErrorId : NativeCommandFailed

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

PS C:\Windows\system32> help
Program 'more.com' failed to run: Object reference not set to an instance of an object.At line:14 char:14
+     $input | more.com
+              ~~~~~~~~.
At line:14 char:5
+     $input | more.com
+     ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (:) [], ApplicationFailedException
    + FullyQualifiedErrorId : NativeCommandFailed

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

PS C:\Windows\system32> get-help get-command -Examples

NAME
    Get-Command

SYNOPSIS
    Gets all commands.

    -------------------------- EXAMPLE 1 --------------------------

    PS C:\>Get-Command


    This command gets the Windows PowerShell cmdlets, functions, and aliases that are installed on the computer.
    -------------------------- EXAMPLE 2 --------------------------

    PS C:\>Get-Command -ListImported


    This command uses the ListImported parameter to get only the commands in the current session.


Get admins with details on list of servers

$
0
0

I am trying to get the list of local administrators for a list of servers, both the local accounts and domain accounts.

I found this script Jeff Hicks wrote and it should work, but it doesn't search for all group members of the local admins group, it also isn't providing the details for the account. 

Can anyone assist? 

get-content servers.txt | foreach {
  [ADSI]"WinNT://$_/Administrator" | select `
  @{Name="Account";Expression={($_.PSBase).Path}},`
  @{Name="PasswordSet";Expression={(Get-Date).AddSeconds(-($_.PasswordAge)[0])}},`
  @{Name="PasswordAge (Days)";Expression={[int](($_.PasswordAge)[0]/86400) }},`
  @{Name="Last Logon";Expression={$_.LastLogin}},`
  @{Name="Days since last login";Expression={`
  (New-TimeSpan -start ($_.LastLogin[0]) -end (Get-Date)).days}}} `
| export-csv "c:\adminage.csv" -notypeinformation 

Need help with syntax please

$
0
0

Trying to figure out how this works because i have a few scripts that have problems - most likely to bad syntax that is not being caught.... 

Reading computer CN out of Active Ditectory, feeding it into the For loop and trying to create a variable using hash table that is within a function. The $Result variable is supposed to contain the Computer name and a word hello. But I cant seem to get the logic correctly for it to return the computer name....

 

Function SetOutputVariable ($Computer){
     $SQLProperties=@{'ComputerName' = $Computer.CN
                                   'Message' = "hello"
                                  }
Return $SQLProperties
}

$Result =`
Foreach ($Computer in $Computers){
            SetOutputVariable -ComputerName $Computer.CN
            New-Object -TypeName psobject -Property $SQLProperties
}

$Result | FT

 

 

Thank you for your help!

Using Listbox with a variable to inject item

$
0
0

I am trying to setup a selection list using $Listbox.Items.Add but I do not want to use static data but rather content from Get-DistributionGroup and have not figured out how to add the content yet. I tried piping to text file but it adds spaces to the DG name which breaks the search.

$listBox.SelectionMode = "Multiextended"

$FullDL = Get-DistributionGroup -anr "x-a" | Format-Table Name

Get-content $FullDL | ForEach-Object {[void] $ListBox.Items.Add($_)}

$form.Controls.Add($listBox)

$form.Topmost = $True

$result = $form.ShowDialog()

Any help would be much appreciated.

 

Email address policy customization, all letters or numbers up to @ sign

$
0
0

Hi there

I am trying to create a script that will check whatever is the primary email for a user

lets say david23@test.corp copy whats before the @ sign and assign a new policy

for example david23@testing.com.

the long story:

I have a lot of users that aren't using the default email policy so they have custom email address that I have no clue what they are(thousands of users like that) so if I modify the default email policy that's based on firstname.lastname@test.corp and just add firstname.lastname@testing.com it wont apply for them, so I have to find away to add the relevant email for these.

more of powershell thing then exchange.

Thanks a lot for any advice

Script to add a group/user to "log on as service" in Windows 2008

$
0
0

I am trying to create a script that automatically adds a group/user to "log on as service" in a Windows 2008 machine. I have tried downlaoding NTrights.exe and using that in cmd but it doesnt work because of the compatibility issue. 

I am now trying to see if its even possible to powershell script? Can anyone advice or help?

UnknownError signing scripts

$
0
0

I'm fairly new to PowerShell and generally having few problems getting things to work. But I have spent a number of hours trying to sign a PowerShell script and need to ask for suggestions about what I could be doing wrong.

To start with, I created a certificate myself like so:
makecert -r -pe -n "CN=TestCodeSigning" -b 04/25/2015 -e 01/01/2099 -eku 1.3.6.1.5.5.7.3.3 -ss My

Verified that the certificate was visible in certmgs.msc with Code Signing enabled as a purpose.

Dropped a .ps1 script into a directory for signing practice.

Executed these commands:

$cert=Get-ChildItem -Path cert:\CurrentUser\my -CodeSigningCert
Set-AuthenticodeSignature -FilePath c:\tempt\LoginMessage.ps1 -certificate $cert   -HashAlgorithm SHA1 

# Also tried variations
$cert2=Get-PfxCertificate "C:\Don\AzureAndWorkStuff\TestCert\mytest.pfx"
Set-AuthenticodeSignature -FilePath c:\tempt\LoginMessage.ps1 -certificate $cert2 -HashAlgorithm SHA1

Also tried
-Force
-Confirm
-IncludeChain all
And versions not specifying hash algorithm

What I get every time is this UnknownError message:

SignerCertificate                                                        Status                  Path                                                            
-----------------                                                              ------                   ----                                                            
7562901B62BD80E8A8C822A55C453419F46FEB96  UnknownError      Test2.ps1        

 

I've been searching online and ran across a comment that saving from the PowerShell ISE produces bad (non-UTF8) encoding. While the first script I tried this on COULD have been saved by the ISE, I have tried saving new scripts from notepad with correct encoding. Yet I get the same error.

Saw another note saying that very small files cannot be signed but my file is a good solid 22 KB.

I noted with surprise that I cannot sign a file without the .ps1 filetype. I figure that's one of the things I'll experiment with when I reach the minimal step of successfully signing something.

Can anyone spot what I'm doing wrong?

Help with regular expression

$
0
0

Hi,

I have string like "abcd_efgh_12345671.log". I need to get only the numbers without the last digit "1", meaning only "1234567" (Marked in bold). The last digit can be any number between 1-9. Can someone help me to find the correct regular expression for this case?

Thanks

Daniel


How to get bitlocker recovery key using command Get-MbamBitLockerRecoveryKey?

$
0
0

Hi all Expert,

I know many ways to get the Bitlocker recovery key from AD. But I really don't know the way to get Bitlocker recovery key from Database. Sometimes AD in my environment is not capture the bitlocker recovery key (not sure why). When I cannot get in AD, I need to mstsc to the database and using SQL query to check that particular machine's recovery key. I search from website I know the powershell command to get the recovery key would be Get-MbamBitLockerRecoveryKey but it just not working when I key in this using powershell in my database server. I try get-help on this command it not showing the full help and I can't download the full help for this command because the powershell is running on database site which I do not have full control on it.

Any one mind to teach me how can I get the recovery key using this command if I only have the machine name or Recovery ID?

 

Rgds,

Liew

 

 

Compare two csv and create third one with a mix of columns from the two csv

$
0
0

Hi,

I need your help.

I have two csv file the first with a lot of columns and 25000 lines the second have only three columns with 1000 lines.

i need to compare the two files with only one property "usualname" it's the same column in the two files. with the  side indicator -eq == , i need to get the other propertys  location, from the first , id from the second corresponding to usualname. and finally create a 3 file with a mix of information from the two files.

$files1= import-csv -path d:\file1.csv -delimiter ","| select-object usualname,location

$files2=  import-csv -path d:\file2.csv -delimiter ","| select-object usualname,room,building,id

compare-object $file1 $file2 -property Usualname -includeequal |where {$_sideindicator -eq "=="}

then i don't have idea so i don't know what i have to do

thank you in advance for your help

regards,

youssef

PowerShell to check files and send e-mail notification

$
0
0

Hello Experts,

I am fairly new to PowerShell, but must say I am impressed by what the tool can accomplish, so I expect to learn a great deal more and become more proficient as time goes on.

Scenario:

I need to check if a certain file exists, was created today, and actually has content.

  • If the file does not exist, or was not created today, an e-mail should be sent that states "File not created" or similar.
  • If the file exists and was created today, but has no content, no e-mail should be sent.
  • If the file exists, was created today, and has content an e-mail should be sent that has the contents of the file in the body of the e-mail.

Reason for this request:

I have to check (and keep in sync) user account status (enabled/disabled) in two Active Directory forrests, for which we unfortunately cannot set up a trust. One is the corporate directory (I'll call it directory A) and the other is a separate forrest used to control system access at one of our facilities (I'll call that directory B). The authoritative directory is directory A. Directory B is managed separately, but contains a subset of the users in directory A, so the user accounts match up to a certain extent. When a user account is disabled in directory A, I need to ensure that the corresponding user account in directory B is also disabled (if the user has an account in directory B that is). I figured out how to automate creating a list of accounts that have been disabled in directory A, but are still active in directory B, (that was fun :-)), but rather than rely on someone to run this manually I would like to automate this solution to run daily and send the e-mails referenced above to whomever needs to receive them.

 

For this example:

  • Folder path = c:\Compare_AD
  • File to check for = Accounts_To_Check.txt
  • smtp server = smtp.mailitsomewhere.net

Any assistance you could offer would be greatly appreciated.

Regards

 

 

Compare-object when comparing an array

$
0
0

I’m migrating two DHCP scopes from two 2008 servers to one Windows 2012 server, which is load balance with another.  The reservations on the old 2008 aren’t the same on both so some get imported and some don’t. I have to merge the two Lease sections of the XML outputs to get one scope to import but I have to sync the missing reservations.  I have a script the pulls the DHCP reservations from the old two and merges them.  Sorts out any duplicates, because some were on both.  Gets the reservations on the new DHCP server and that were it goes wrong

I need to use Compare-Object I get this out

InputObject                                       SideIndicator

-----------                                              -------------

DhcpServerv4Reservation           <=                                                                             

DhcpServerv4Reservation           <=                                                                             

DhcpServerv4Reservation           <=                                                                              

DhcpServerv4Reservation           <=                                                                             

DhcpServerv4Reservation           <=       

This is my script so I suppose my question is when I sort and array of object how can I just pick say IP and leave me with just the ones that aren’t on DCHP01 and run those through the FprEach-Object loop

$DC01=Get-DhcpServerv4Reservation-ScopeId172.26.32.0-ComputerNamedc01

$DC03=Get-DhcpServerv4Reservation-ScopeId172.26.32.0-ComputerNamedc03

$DHCP01=Get-DhcpServerv4Reservation-ScopeId172.26.32.0-ComputerNamedhcp01

$Reservations=$DC01+$DC03

$Reservations=$Reservations|Sort-ObjectName|select-UniqueName,IPAddress,ScopeID,ClientId,Description

$Different=Compare-Object$Reservations$DHCP01

 

#$Different | ForEach-Object{

#Add-DhcpServerv4Reservation -ClientId $_.ClientId -IPAddress $_.IPAddress -ScopeId $_.ScopeId -ComputerName DHCP01 -Description $_.Description -Name $_.Name -Type Both

#}

 

This the data in my $DC01, $DC03 and $DHCP01 strings

PS C:\Windows\system32> Get-DhcpServerv4Reservation -ScopeId 172.26.32.0 -ComputerName dc01

 

IPAddress            ScopeId              ClientId             Name                 Type                 Description        

---------            -------              --------             ----                 ----                 -----------        

172.26.32.182        172.26.32.0          78-e3-b5-fa-4f-e2    mfp60901. Both                                    

172.26.32.5          172.26.32.0          00-27-0e-38-98-75    PC61045.  Dhcp                 Mike Waldron's PC  

172.26.32.193        172.26.32.0          00-21-5a-96-d1-b2    MFP60872. Both                                    

172.26.32.109        172.26.32.0          14-58-d0-39-1b-0d    MFP60892. Dhcp                                     

172.26.32.113        172.26.32.0          64-51-06-27-70-be    MFP60857. Dhcp                                    

PS C:\Windows\system32> Get-DhcpServerv4Reservation -ScopeId 172.26.32.0 -ComputerName dc03

IPAddress            ScopeId              ClientId             Name                 Type                 Description        

---------            -------              --------             ----                 ----                 -----------         

172.26.32.182        172.26.32.0          78-e3-b5-fa-4f-e2    mfp60901. Dhcp                                    

172.26.32.5          172.26.32.0          00-27-0e-38-98-75    PC61045.  Dhcp                 Mike Waldron's PC  

172.26.32.177        172.26.32.0          dc-9c-52-16-f5-47    SWEP5.    Dhcp                                    

172.26.32.156        172.26.32.0          08-00-27-7f-79-ac    PC60197VM.york.go... Dhcp                 Steve Fentons VM   

172.26.32.178        172.26.32.0          00-50-b6-62-5d-34    LT63347.  Dhcp                 D Andrew Laptop    

172.26.32.166        172.26.32.0          00-50-b6-60-9e-80    LT63346.  Dhcp                 S Binns Laptop     

172.26.32.160        172.26.32.0          54-ee-75-0f-18-b3    PC64792.  Dhcp                 Reddy Rakasi - To...

PS C:\Windows\system32> Get-DhcpServerv4Reservation -ScopeId 172.26.32.0 -ComputerName dhcp01

IPAddress            ScopeId              ClientId             Name                 Type                 Description        

---------            -------              --------             ----                 ----                 -----------        

172.26.32.160        172.26.32.0          54-ee-75-0f-18-b3    PC64792.  Dhcp                 Reddy Rakasi - To...

172.26.32.5          172.26.32.0          00-27-0e-38-98-75    PC61045.  Dhcp                 Mike Waldron's PC  

172.26.32.156        172.26.32.0          08-00-27-7f-79-ac    PC60197VM.york.go... Dhcp                 Steve Fentons VM   

172.26.32.166        172.26.32.0          00-50-b6-60-9e-80    LT63346.  Dhcp                 S Binns Laptop     

172.26.32.177        172.26.32.0          dc-9c-52-16-f5-47    SWEP5.    Dhcp                                    

172.26.32.178        172.26.32.0          00-50-b6-62-5d-34    LT63347.  Dhcp                 D Andrew Laptop    

172.26.32.182        172.26.32.0          78-e3-b5-fa-4f-e2    mfp60901. Dhcp    

 

Dealing with parsing

$
0
0

I found this example:  ("OU=MTL1,OU=CORP,DC=FX,DC=LAB" -split ",")[0].substring(3)  when I run this it returns MTL1.  It uses the comma as the split.  I changed all of the comma's to backslashes ("OU=MTL1\OU=CORP\DC=FX\DC=LAB" -split "\")[0].substring(3) and it fails with this error:  parsing "\" - Illegal \ at end of pattern.

Why?

I need to parse our PATH statement.  We deployed some software which worked but it added a path to the Beginning of the path statement on every workstation and now, if you open up a CMD window and type in anything like MSIEXEC or XCOPY it can't find it.  You have CD to the %System32% folder and then run them for things to work.  But if I remove the path this program added to our PATH statement and add it to the very end it all works.  

So I have this:

$find = "C:\Program Files\WebEx\Productivity Tools"

$WinPath = Get-ChildItem Env:path

I need to find "C:\Program Files\WebEx\Productivity Tools" and delete it.  and then add it to the very end of the path.    But it does not like the backslash

 

 

 

 

Report of members of local Administrators group

$
0
0

I found this here: (http://powershell.com/cs/media/p/376.aspx)

  1. cls 
  2. $ErrorActionPreference="SilentlyContinue" 
  3. Get-Content (ENTER PATH TO YOUR INPUT FILE HERE) | foreach
  4.     [ADSI]"WinNT://$_/administrator" | select ` 
  5.     $(Name="Account";Expression={($_.PSBase).Path}}, ` 
  6.     $(Name="Password Set";Expression={(Get-Date).AddSeconds(-($_.PasswordAge)[0])}}; ` 
  7.     $(Name="PasswordAge (Days)";Expression={[int]((4-.PasswordAge)[0]/86400) }}, ` 
  8.     $(Name="Last Logon";Expression={$_.LastLogin}}, ` 
  9.     $(Name="Days Since Last Logn";Expression={ ` 
  10.     (New-TimeSpan-start ($_.LastLogin[0]) -end (Get-Date)).days}}} ` 
  11. | Export-csv (ENTER PATH TO YOUR OUTPUT FILE HERE) -notypeinformation 

The $'s in the SELECT statement need to be @'s... That corrected, I'm trying to get to run so I can report on the local administor account - by SID.  Our local admin accounts are renamed depending on department.   Also to run against all (local account) members of the builtin administrators group.

I've been able to dump the members, but am having trouble putting the two halves together.  

 

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

 

 

 

 

 

 

Inbox Rules with multiple email-addresses in From parameter

$
0
0

Exchange 2010 SP3. I need to use the -From parameter in the Set-InboxRule Cmdlet with more than one address, but I can't get it to work. This is how I would have hoped it would work:

Set-InboxRule <RuleName> -Mailbox <Mailbox> -From "email-address1,email-address2"

But seems to me that email-address2 is ignored. Tried different delimiters with same result.

Can you Guys help me figure out, how to assign a multi-address value to the -From parameter? Thanks! :)

Get-MailboxStatistics -Server with -Archive doesn't work for me

$
0
0

I must be doing something wrong but here is my issue:

 

Get-MailboxStatistics -Server "exnameofserver"  #works fine and returns data

Get-MailboxStatistics -Server "exnameofserver" -Archive   #throws this error: "Parameter set cannot be resolved using the specified named parameters"

Same issue with -Database param btw

I know I can run a foreach with Identity but that will take 5 hours on the archives when the primarys data returns in a matter of a couple of minutes with all info I need.

Anyone know what I am doing wrong or a better way than foreach and 5 hours???

 

import users from database into active directory group

$
0
0

Trying to write powershell script to populate a group of users on a specific databse to an Active Directory group.  User in the database are in a child domain, the parent domain contains the group.

 

I have:

Import-Module ActiveDirectory

$ADGroup = "CN=testgroup,DC=test,DC=com"

$Users = get-mailbox -database server\database -IgnoreDefaultScope | select samaccountname

Add-ADGroupMember -Identity $ADGroup -Members $Users

Find enabled users in a given mailbox database

$
0
0

Get-Mailbox doesn't take parameter that filters by enabled/diabled

Get-ADUser doesn't take a parameter that filters by mailbox database

I tried

Get-Mailbox -Database db02 | Get-ADUser -LDAPFilter "(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2))"

but that seems to return all enabled users and the second part doesn't seem to limit the input to the output of the first part.

Any ideas how this can be accomplished?

Viewing all 10624 articles
Browse latest View live