Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

to set up auto out of office reply for disabled/deprovisioned Active Directory users

$
0
0
We would like to set up auto out of office reply for disabled/deprovisioned Active Directory users. Is there a power shell script that I can use?

When using the Get-Mailbox command for pst import, how should the pst be named?

$
0
0

When trying to import multiple .pst files, example below, would the .pst's need to be named the alias of what the users account is?  

Get-Mailbox –Database "Mail\First Storage Group\Mailbox Database" | Import-Mailbox –PSTFolderPath D:\UserPSTs

Display Get-Process with ListView

$
0
0

I'm experimenting with PowerShell and trying to learn more about it. So far I've grasped the basics and am now trying to use it in conjunction PrimalForms to create a GUI. What I want to do is, with the press of a button, neatly display all currently running processes, similarly to the task manager.

I would like it to have three columns, one for the process' name, one for its CPU load and a third for the ID.

$sampleForm = New-Object System.Windows.Forms.Form
$sampleForm.Width = 300
$sampleForm.Height = 300

$listView = New-Object System.Windows.Forms.ListView
$listView.View = 'Details'
$listView.Width = 300
$listView.Height = 300

$listView.Columns.Add('ID')
$listView.Columns.Add('Process name')
$listView.Columns.Add('CPU Load')

Get-Process | %{
    Add-ListViewItem -ListView $listView `
        -Items $_.ID`
        -SubItems $_.ProcessName, $_.CPU
}

$sampleForm.Controls.Add($listView)
[void] $sampleForm.ShowDialog()

So far I've done it less elegantly with the above code, it works by itself but not when I combine it with the code generated by PrimalForms. Together with the code from PrimalForms the ListView output will only output all the processes, but not create the columns. How can I create these columns and properly place everything where it should be? Any help is greatly appreciated!


Invoke-Command and Get-WindowsFeatures

$
0
0

Hi,

I'm having some difficulty writing a little script. I want to accomplish that the installed Windows Roles and Features correspond to an inputfile locally on the remote machine which contains the names of the Windows Roles and Features. Sample of the input file:

Application-Server
AS-NET-Framework
Remote-Desktop-Services
RDS-RD-Server
Web-Server
Web-WebServer etc. etc.

This is what I got:

$computername="SERVER" invoke-command -ComputerName $computername -scriptblock { import-module ServerManager if (!(test-path -IsValid "E:\rolesandfeatures.txt")) { write-host -foregroundcolor red "E:\rolesandfeatures.txt does not exist `n Skipping Roles and Features"} Else { $RolesAndFeatures=get-content "E:\rolesandfeatures.txt" foreach ( $RA in $RolesAndFeatures ) {

$check = Get-WindowsFeature -name $RA | where-object { $_.Name -eq $RA } write-host $check }}}

When I run the $check = Get-WindowsFeature -name $RA | where-object { $_.Name -eq $RA }locally on a server $check contains the names of the installed Roles and Features. When I run it remote $check only containsMicrosoft.Windows.ServerManager.Commands.Feature.

What can I do to get the $check variable filled with the name of the remote Role of Feature?

Hope somebody can help.

Thanks,

Mark

 



   

FilterBased on Extended Attributes (employeeNumber) and Dispaly sAMAccountName

$
0
0

I have a list of employee numbers and want to get sAMAccoutName and use those in a script to terminate accounts. Below is what I managed to put together but it does not give me what I want. Any help would be greatly appreciated.

Get-QADUser -DontUseDefaultIncludedProperties -IncludedProperties sAMAccountName -LdapFilter "(&(objectCategory=person)(objectClass=user)(employeeNumber=00014772))"

Name                       Type            DN
----                           ----              --
Doe, John                user            CN=Doe\, John,OU=USR,OU=USMD1,OU=US,OU=Regions,OU=Accounts,DC=m...

Instead of it displaying "Doe, John", I want it to display "DoeJ"

Thank you

Using Microsoft.Powershell.Commands fails on Server 2008 R2 with Powershell 3.0 installed

$
0
0

I have a simple script that checks the EnhancedKeyUsageProperty of a certificate installed on a local machine. If a specific Root CA gets enabled, sites for the client fail so I am querying to ensure that the result set is Null. This works fine on a Win8 or Server 2012 machine but always returns Null on a Win 2008R2 server. Any ideas on how I can modify this to get it to return data on Server 2008 R2?

$path = "c:\temp\cert_status.txt"

$cert = dir Cert:\LocalMachine\Root\91C6D6EE3E8AC86384E548C299295C756C817B81
$eku = New-Object Microsoft.PowerShell.Commands.EnhancedKeyUsageProperty $cert | Out-File $path
if ($eku=$null) {
Send-MailMessage -From "sender@example.com" -To "me@example.com" -Subject "Primary Root CA is disabled" -Body "The certificate is disabled" -SmtpServer localhost
}
else {
Send-MailMessage -From "sender@example.com" -To "me@example.com" -Subject "Primary Root CA is enabled" -Body "The certificate is enabled" -SmtpServer localhost
}

File Verification - If File Exists Continue - If Not Quit

$
0
0

Hello,

I'm having a little issue, below is an abstract from my script...

Enter-PSSession $compname
cd c:\local\NewLocalProfile
$tname = Read-Host "Enter Target Username"
takeown /F c:\users\$tname
New-Item  -ItemType File - Path c:\users\$tname\appdata\local\stampt.txt
robocopy c:\users\$tname c:\local\profilebackup\$tname /E /ZB /COPY:DAT /XJ /TEE /R:1 /W:1

(Get-WmiObject Win32_UserProfile | Where {$_.LocalPath -Match $tname}).Delete()

You can see on Line 5 a .txt file is created, and then a backup is done using ROBOCOPY, on line 7 i would like a statement to check the .txt file created in line 5 exists in the copied location... If it does i want it to continue to the WMI stage, and if not, i want the script to end with a Warning advising it's not completed.

I have had a look around but cannot find any statements online for if existing continue, if not error... has anyone got any ideas?

In the days of DOS i would use 

IF NOT EXIST C:\local\profilebackup\%username%\appdata\local\stamp.txt GOTO :failure
IF EXIST C:\local\profilebackup\%username%\appdata\local\stamp.txt GOTO :Continue

Making reference points in my script, but can't seem to get my head around this in PowerShell.

Help would be much appreciated.

:)

Thanks!

Calling MSBuild through a remote Invoke

$
0
0

I'm trying to write some remote deploy scripts.  I'm using a powershell script to copy an MSI, run the MSI, and then run an MSBuild script afterwards (this is a BizTalk install so I'm running a .btproj file).  The script works fine locally, but when run remotely, when it attempts to execute the MSBuild script, I get a "WriteErrorException".  I'm guessing that I'm running into some kind of permission issues when launching the MSBuild remotely, but I can't find any answer to this problem. 

I'm currently doing a "Start-Process" and passing the "-Verb runas" argument, but that doesn't seem to be making any difference.

Thanks,

Shawn


Shawn Morgan Blue Arch Solutions, Inc. shawn.morgan@bluearchsolutions.com


Remote Script Execution

$
0
0

I have a script (install.ps1) which uses functions from another script (Functions.ps1) using dot source. I am trying to execute the install.ps1 on a remote server using Invoke-Command. However it fails with error 

 
The term '.\Functions.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.+ CategoryInfo          : ObjectNotFound: (.\Functions.ps1:String) [], CommandNotFoundException+ FullyQualifiedErrorId : CommandNotFoundException


My install.ps1 looks like as follows:

. .\Functions.ps1

Write-Host 'Executing script remote'
FunctionA "Test"


This script works fine locally, also I am able to execute the script remotely which does not use dot source. The command I am using to execute it remotely is

Invoke-Command -computername <servername> -filepath Install.ps1 -Credential $c

What are the options I have to fix this issue? Please help

Create Team Foundation WorkItem with PowerShell

$
0
0

Hello,

I want to create a work item from type task when a build quality is changed to a special value.

How can I do something with powershell? I hope somebody can help me and bring me on the right way to do such scenario.


Thanks Horst MOSS 2007 Farm; MOSS 2010 Farm; TFS 2010; IIS 7.5

Update Regional Location Powershell

$
0
0

Hi,

I have applied kb273125 to my server 2008 servers to add South Sudan to the list of Recognized Countries.

From the info I can find Exchange 2010 appears to pull country information from Powershell and not from the windows server and as such does not recognize South Sudan and gives the error below.

Warning:

The object  has been corrupted, and it's in an inconsistent state. The following validation errors happened:

Warning:

Cannot calculate value of property "CountryOrRegion": "Cannot parse a Country/Region from the ISO-3166 2-letter country/region code "SS", country/region code "0" and friendly name "South Sudan"."

Is anyone able to advise how I can get Powershell to recognize South Sudan To stop me getting the object corrupted message.

Any Help Greatly Appreciated

Kieran Billing


How to Get Mailbox First activity and last activity

$
0
0

Is it possible to get first and last mail item created in the mailbox???

Is there any powershell cmdlets there to get these values???

or

Is it possible to values using EWS managed API???

If statement question

$
0
0

Would anyone know why my function works except for the first "If" statement I have in the process block?I swear all of this worked last night...

#Gets Java version from a computer list entered by parameter or .csv path

function GetJavaVersionWork {
  param([string]$ComputerName)

    Try
    {
      Write-Host "Checking computers for Java versions on $Computer.." -ForegroundColor Cyan     
      
        Invoke-Command -ComputerName $Computer -ThrottleLimit 100 -ScriptBlock {

        
          $ComputerName = gwmi win32_operatingsystem -Property csname | select -expand csname      
          $ChkJavaVersion = gwmi win32_product -Filter "name like '%java%'" | select -expand version


          
                if ($ChkJavaVersion -eq $Null)
                {

                    Write-Host "Java is not installed on $ComputerName" -ForegroundColor Red
          
                }


          $Obj = New-Object -TypeName psobject
          $Obj | Add-Member -MemberType NoteProperty -Name "Computer" -Value $ComputerName
          $Obj | Add-Member –membertype NoteProperty –name "Java Version" -value $ChkJavaVersion

                


          $Obj

        
        } -ea Stop | select 'Computer' , 'Java Version' | Export-Csv C:\JavaList.csv -Append

    }
        
       
      
    Catch
    {
          
      Write-Host "Logging error to file.." -ForegroundColor Red
      $_ | Out-File c:\Errors.txt -Append
        
    }


}


function Get-JavaVersion {
  [CmdletBinding()]
  param (
          [string[]]$ComputerName,
          [string]$CSVPath
)

      
      BEGIN {
        DEL c:\JavaList.csv -ea SilentlyContinue
        DEL c:\JavaList.txt -ea SilentlyContinue
        DEL c:\errors.txt -ea SilentlyContinue
      }
 
    
    
      PROCESS {


    
      if (($ComputerName -eq $Null) -and ($CSVPath -eq $Null))
      {
          
           Throw New-Object System.ArgumentException("You MUST enter a computer name OR a .csv path")
      
      }


             elseif (($ComputerName -eq $Null) -and ($CSVPath -ne $Null)) {
                
               
                    $ComputerList = Import-Csv $CSVPath | select -ExpandProperty ComputerName
                 
                    
                    foreach ($Computer in $ComputerList) {
                    
                        
                       if (Test-Connection -ComputerName $Computer -Count 1 -Quiet)
                       {
              
                           GetJavaVersionWork -ComputerName $Computer
          
                       }


                       
                      else
                      {
             
                          Write-Host "Cannot connect to $Computer. Logging $Computer to file.." -ForegroundColor Red
                          $Computer | Out-File c:\comps.txt -Append
          
                      }

            
                 }

           
            }

      
            
             elseif ($ComputerName -ne $Null) {         
       
        
                foreach ($Computer in $ComputerName) {  
       
                
                  if (Test-Connection -ComputerName $Computer -Count 1 -Quiet)
                  {
              
                      GetJavaVersionWork -ComputerName $Computer
          
                  }
           
          
                  else
                  {
             
                      Write-Host "Cannot connect to $Computer. Logging $Computer to file.." -ForegroundColor Red
                      $Computer | Out-File c:\comps.txt -Append
          
                  }
   
            }
 
       }

  }

 
    END {
      Write-Host "Operation complete!" -ForegroundColor Yellow
    }

}
Get-JavaVersion

Powershell 3.0 Workflows

$
0
0
Is there tool which allows a more visual creation of powershell 3.0 workflows? Like a visual studio extension or something?

val it: unit=()

Finding when a Exchange Store last backed up via script

$
0
0

Dears, 

 has posted a script here Website  that could be useful to check when was the last time each Database has been backed up, the code goes like this 

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

On Error Resume Next
set conn = createobject("ADODB.Connection")
set mdbobj = createobject("CDOEXM.MailboxStoreDB")
set pdbobj = createobject("CDOEXM.PublicStoreDB")
set com = createobject("ADODB.Command")
Set iAdRootDSE = GetObject("LDAP://RootDSE")
strNameingContext = iAdRootDSE.Get("configurationNamingContext")
Conn.Provider = "ADsDSOObject"
Conn.Open "ADs Provider"
mbQuery = "<LDAP://" & strNameingContext & ">;(objectCategory=msExchPrivateMDB);name,distinguishedName;subtree"
pfQuery = "<LDAP://" & strNameingContext & ">;(objectCategory=msExchPublicMDB);name,distinguishedName;subtree"
Com.ActiveConnection = Conn
Com.CommandText = mbQuery
Set Rs = Com.Execute
Wscript.echo "Mailbox Stores"
Wscript.echo
While Not Rs.EOF
mdbobj.datasource.open "LDAP://" & Rs.Fields("distinguishedName")
Wscript.echo Rs.Fields("name") & " Last Backed Up : " & mdbobj.LastFullBackupTime
wscript.echo 
Rs.MoveNext

Wend
Wscript.echo "Public Folder Stores"
Wscript.echo
Com.CommandText = pfQuery
Set Rs1 = Com.Execute
While Not Rs1.EOF
pdbobj.datasource.open "LDAP://" & Rs1.Fields("distinguishedName")
Wscript.echo Rs1.Fields("name") & " Last Backed Up : " & pdbobj.LastFullBackupTime
wscript.echo 
Rs1.MoveNext

Wend
Rs.Close
Rs1.close
Conn.Close
set mdbobj = Nothing
set pdbobj = Nothing
Set Rs = Nothing
Set Rs1 = Nothing
Set Com = Nothing
Set Conn = Nothing


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

My question is: is there any way to enable the script to read all Exchange Servers in the organization from a file ?

Regards,






Signing scripts - how to generate a CSR for dummies?

$
0
0

I know this isn't strictly a PowerShell question, but this seems the best place to ask this because...

  • I am not a developer! (and I don't want to be one.)
  • We don't run IIS.
  • We don't have a PKI or the ability to create one.

I often have fairly simple PowerShell scripts I would like users/computers in the (sub)domain I manage to run while maintaining some semblence of security (AllSigned execution policy).  We can request certificates from a third-party CA, but I have to generate a code signing CSR first (is this different than a SSL CSR?).

I understand the basic concepts of code signing (private/public key pairs, time stamping, Root CAs, etc.), and I can find information on how to sign the scripts once I have a certificate, but I don't know the mechanics of getting to that point.  There is information (though inconsistant, rather convoluted and old) on creating self-signed certificates, but I would like to have all the machines/users in the subdomain trust the certificates.  I'm not opposed to generating a self-signed certificate if there is a way (that I can follow and without a PKI) to elevate that certificate to be trusted by computers/users in the domain.

Does anyone know of or can someone create a step-by-step tutorial on the mechanics of generating a CSR to get a code-signing certificate for non-developers?

Even better would be a (up-to-date) tutorial on the whole process of generating a CSR, acquiring a publicly trusted cert, installing/securing the cert, and signing (and dating) PowerShell scripts.  I can't imagine that I am the only system admin in this situation and if we could whip up a signed, script to give to users/computers under our management while only minimally relaxing the execution policy, I think we could all be more secure and efficient.

Thanks.

How to check if an AD attribute is not set

$
0
0

Hi,

I'm guessing this is pretty easy when you know how, but I don't know the syntax. I'm querying AD and want to process users in an OU, but I only want to process users who have proxyAddresses set. How can I do this? Currently my code falls over whenever a user with the proxyAddresses not set is present in my OU. The "=*" hasn't worked

Thanks

Import-ModuleActiveDirectory

$users=([ADSI]"LDAP://OU=test,OU=FIMObjects,OU=Accounts,DC=mydom,DC=local").PSBase.Children

Foreach($userin$users){

#only run on user if attribute exists

if($user.get("Proxyaddresses")=*)

{}}

Powershell nesting help

$
0
0

I have the following code which works like a dream to find the relevant mac address and changes the network adapter name:

$macaddress = "%macaddress%"
$newname = "%networkname%"
$NicInterfaceName = get-wmiobject Win32_NetworkAdapter | where {$_.macaddress -eq "$macaddress"}
$NicInterfaceName.netconnectionid = "$newname"
$NicInterfaceName.put()

I want to make this code exist on one line, I know I could remove the variables, which obviously i'll do.

Help :)

Changing Local Admin Password

$
0
0

I'm writing a script to automate my server builds.  part of the script is changing the local administrator password.  I'm trying to save the password as a secure string into a txt file and then after a few reboots I will invoke that password to change the local administrator password.  This is what I have but it's not working.  If I just type a random password in, it works, but when pulling in a secure string from a txt file it is failing

So first I set the password like this

read-host -assecurestring | convertfrom-securestring -Key (1..16) | out-file c:\admin.txt

Then on a later script I do

$adminpass = gc C:\admin.txt | ConvertTo-SecureString -Key (1..16)
$strcomputer = "."
$admin=[adsi]("WinNT://" + $strcomputer + "/username,user")
$admin.psbase.invoke("SetPassword","$adminpass")

Thanks

Generate Excel which Shows ADUsers and his Groups in a Matrix with AllGroups

$
0
0

Hi There.

I Need an Excel table for managemet, which Shows the following:

The Colums should be named as Username ActiveDirectory and some Properties and ALL Groups which are availible in Active Directory

Each row should then contain Username and in the Column of Group an "X" or somthing else, if the user is in the Group - like a Matrix.

Username,Firstname,Lastname,Group1,Groups2,Group3,Group4...

Username1,Firstname1,Lastname1,,x,,x.. -- User1 is in Group2 and Group4

Username2,Firstname2,Lastname2,x,x,x,x... -- User2 is in Group 1-4

I thought about generating an Hashtable with all AD-Groups and a Hashtable with User and his AD-Groups, but I don't know how to match them.

Have anyone an idea?

Thanks.

Viewing all 21975 articles
Browse latest View live




Latest Images