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

setting a variable

$
0
0

Hello, 

I am looking to use the value of the object in the query below as a variable in my script. 

$a = Get-WmiObject win32_bios | select-object __SERVER

Currently $a returns 

__SERVER
--------

HPWC102043

How can I make it only the value "HPWC102043" ? 

cheers


Email password age with Powershell

$
0
0

Morning Guys

I'm hoping someone can assist me or point me in the right direction.

I have modified a script but can't get it to work 100%. 

I would like my script to email everyone with their password age once their password is older than 30 days. Their passwords are configured to not expire, but they still want to receive their password age so they can change it once it reaches 30 days. 

The script I have below works in that it gets the password last set, but I am unable to convert it to password age. It also doesnt seem to email once it's older than 30 days, it seems to generate the password last set no matter what I change the value to.

Could anyone assist or point me in the right direction please?

Thanks for your help

Regards

Gordon

##################################################################################################################
#Please Configure the following variables....
$smtpServer="10.0.0.1"
$from = "administrator@xyz.com"
#$expireindays = 15
###################################################################################################################

#Get Users From AD who are enabled
Import-Module ActiveDirectory
$users = get-aduser -filter * -properties * |where {$_.Enabled -eq "True"} | where { $_.PasswordNeverExpires -eq $True }

foreach ($user in $users)
{
  $Name = (Get-ADUser $user | foreach { $_.Name})
  #$emailaddress = $user.emailaddress
  $passwordSetDate = (get-aduser $user -properties * | foreach { $_.PasswordLastSet })
  #$maxPasswordAge = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge
  #$expireson = $passwordsetdate + $maxPasswordAge
  $today = (get-date)
  $subject="Your password is $passwordSetDate days old - Please consider changing it"
  $body ="
  Dear $name,<p> Your password is $passwordSetDate days old.<br>
      Please consider changing as soon as you log in to the Bybrook Capital network. <br><p>To change your password: once logged in, press CTRL-ALT-DEL and select the 'Change password' option. <br><p>Regards, <br><p> IT Administrator <br></P>"

  if ($passwordSetDate -gt 30)
  {
    Send-Mailmessage -smtpServer $smtpServer -from $from -to $emailaddress -subject $subject -body $body -bodyasHTML -priority High
  }

}

get-help for functions with dynamic parameters in a user module

$
0
0

I have a user module I'm writing, that I'm trying to document with inline/comment-based help.

A function in the module:

<#
.Synopsis
   Get-CBSNoun returns information about the nouns in the CBS system. You use Get-CBSNoun
   to get a list of the available items that you can invoke operations on in the system.
.DESCRIPTION
   If you don't specify a noun, this function returns all the nouns in the system. If you
   specify a noun, it returns all of those nouns available in the system. The method of
   construction for this function was based on the Get-Help cmmdlet, so no params returns
   all the nouns and a specific one returns information about that one.
.PARAMETER Noun
    Optional. The noun you want information about.
.EXAMPLE
   Get-CBSNoun
.EXAMPLE
   Get-CBSNoun -Noun Product
#>
function Get-CBSNoun
{
    [CmdletBinding()]
    [OutputType([string])]
    Param
    ($dummyparam)
    DynamicParam {
        $ParameterName = 'Noun'
        # Create the dictionary
        $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary

        # Create the collection of attributes
        $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]

        # Create and set the parameters' attributes
        $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
        $ParameterAttribute.Mandatory = $false
        $ParameterAttribute.Position = 1
        $ParameterAttribute.ParameterSetName = "__AllParameterSets"

        # Add the attributes to the attributes collection
        $AttributeCollection.Add($ParameterAttribute)

        # Generate and set the ValidateSet
        $arrSet = (Get-Item $PSScriptRoot\*.csv).BaseName
        $ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet)

        # Add the ValidateSet to the attributes collection
        $AttributeCollection.Add($ValidateSetAttribute)

        # Create and return the dynamic parameter
        $RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection)
        $RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter)

        return $RuntimeParameterDictionary
    }

    Begin
    {
        $noun = $PsBoundParameters[$ParameterName]
        Write-Verbose $PSScriptRoot
    }
    Process
    {
        if ($noun)
        {
            switch ($noun)
            {
                Default
                {
                    Write-Verbose "Noun to search is: $noun"
                    $pathToSearch = "$PSScriptRoot\$noun.csv"
                    Write-Verbose "Generated path to search is: $pathToSearch"
                    if (Test-Path $pathToSearch)
                    {
                        Write-Verbose "Test-path for $pathtoSearch passed"
                        import-csv $pathToSearch
                    }
                    else
                    {
                        $errorMessage = "No noun: $Noun found"
                        throw $errorMessage
                    }
                }
            }
        }
        else
        {
            (Get-Item $PSScriptRoot\*.csv).BaseName | select @{Name='Noun';Expression={$_}}
        }
    }
    End
    {
    }
}

But when I run:

> get-help Get-CBSNoun -full

I don't see any information about the 'Noun' parameter.  $DummyParam is there.  But Noun is missing.

Further, get-help appears completely ignorant of the dynamic parameter:

PS Function:\> get-help get-cbsnoun -parameter noun
get-help : No parameter matches criteria noun.
At line:1 char:1
+ get-help get-cbsnoun -parameter noun
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (System.Manageme...CommandHelpInfo:ProviderCommandHelpInfo) [Get-Help], PSArgumentException
    + FullyQualifiedErrorId : NoParmsFound,Microsoft.PowerShell.Commands.GetHelpCommand
 

What do I need to do to either:

a) the comment based help

b) the dynamic parameter creation

c) other parameters passed to get-help

to make this work as I'm expecting?

Thanks kindly!

can I wait-job in a powershell job?

$
0
0

i want to wait a job complete and  then do something (the wait i want to use anothing job) but always errors

Start-Job -ScriptBlock {sleep -Seconds 300} -OutVariable mm
Start-Job -ScriptBlock {param($job) Wait-Job -id $job.id ;write-output "here"} -ArgumentList $mm




yoke88
IM:yoke-msn@hotmail.com


Script doesn't work in task scheduler

$
0
0

I know it has already posted many times but I have already tried everything and still I can't get it to work.

The script is a simple send email function and it works if executed from the command prompt:

powershell.exe -f .\sendEmail.ps1 test@test.com "Test Subject" "Test Message"

But in the task scheduler it doesn't work and no email is sent. The exit code of the task is 0xFFFD0000:

Task Scheduler successfully completed task "\SendEmailTest" , instance "{15ff2070-ee25-4b2e-9ae1-274eda0d8c3a}"

, action "powershell.exe" with return code 4294770688.

The task is configured to run under the SYSTEM account with highest privilege, powershell ist configured with unrestricted execution policy, why it doesn't work?

I have tried also with a simpler task to create a text file

New-Item c:\scripts\new_file.txt -type file -force -value "This is text added to the file"

But it doesn't work too, so it should be some other missing privilege somewhere but I couldn't find anything in internet.

Thanks for any help

PowerShell import Data from csv, but mail will not add

$
0
0

The mail is not working. 

Help!

Import-CSV ".\Project W2k8-Server AD - Gebruikers2.csv" | Select-Object Roepnaam,Achternaam,tussenvoeg,Persoonsnummer,Functie,Indienst ,`
    @{name='name';expression={$_.'Persoonsnummer'}},`
    @{name='mail';expression={$_.'E-mail'}},`
    @{name='userPrincipalName';expression={$_.'Persoonsnummer' + '@drachten.local'}},`
    @{name='sAMAccountName';expression={$_.'Roepnaam'}},`
    @{name='givenName';expression={$_.'Roepnaam'}},`
    @{name='surname';expression={$_.'tussenvoeg'+' '+$_.'Achternaam'}},`
    @{name='displayName';expression={$_.'Roepnaam'+' '+$_.'Achternaam'}},`
    @{name='department';expression={$_.'Functie'}},`
    @{name='description';expression={$_.'Indienst'}},`
    @{name='path';expression={'OU=Test,DC=drachten,DC=local'}} |
    New-ADUser -ChangePasswordAtLogon $True -Enabled $True -AccountPassword $(ConvertTo-SecureString "Qwerty1" -AsplainText -Force)

Project W2k8-Server AD - Gebruikers2.csv:
Roepnaam,Achternaam,tussenvoeg,Persoonsnummer,Functie,E-mail,In dienst,
Laurens,Post,,1920817902,Productie medewerker,xx@newwave.nl,8/1/2008,

 

convert to array

$
0
0

how do I convert a text file to an array variable?

text file is

1

2

3

4

I want to convert to

$array=@("1","2","3","4")

Powershell - Monitor AD Groups

$
0
0
Hi All

I would like to know when a user has been added to and removed from a group in Active Directory.

Is there a powershell script (or two separate scripts) that can show this information?

Thanks

Ivan

Need to extract active directory info

$
0
0
Hi, I need to extract what user is using which pc on an active directory domain using powershell, please help

Why does my WPF UI Freezes when trying to update ListBox?

$
0
0

I am having problems when trying to use Register-EngineEvent to update a listBox in a different runspace. (Line 32)http://pastebin.com/JuY5KfP4[1]

When the Search button is pressed it triggers an event to write 'Event Happened' to console and it should return 'Test' to the UI ListBox. However, the part of the event that should be updating the ListBox is causing the UI to freeze.

I got a single thread version of this to work, however, my UI would freeze while doing a complex search (in my case a Get-ChildItem on a big directory). This is how I came across using different Runspace's. http://learn-powershell.net/2012/10/14/powershell-and-wpf-writing-data-to-a-ui-from-a-different-runspace/[2]

I have found someone with a very similar problem: http://stackoverflow.com/questions/23699507/why-does-this-code-freeze-my-wpf-ui[3] but I could not find a solution or an explanation.

PS version: 4.0

This is new territory to me so please forgive me if I use the wrong terminology. 

Thank you for your time.


How to pass multiple arrays as arguments to a Powershell script ?

$
0
0

Hello all,

I need to pass several arrays as arguments. Each array is a computer group and I want to have the args[] array with multiple arrays inside.

Example : Powershell.exe -File "myscript.ps1" (computer1,computer2,computer3) (computer8,computer9,computer10) (computer12,computer18,computer19)

Could you helpmeto findthe right syntax?

Kind regards


Difference between $string -match "regpattern" and $regobj = [System.Text.RegularExpressions.Regex] "regpattern"

$
0
0

Hi,

I've to parse a logfile which is going fine so far. However I faced a difference of results while using $string -match or using the .net object with [RegEx].

I prefer to use .net as I can easily access the values and get more than one match if they are.

logfileA (all separated lines):
5/6/2015 10:33:02 PM Cannot delete folder: E:\FRPAR\Home\fr10038\Symantec_Ghost_Solution_Suite_2.0.1_AllWin_EN\Symantec Ghost Installer Job Name: FRPAR -> DELIN_Home 
5/6/2015 10:33:02 PM Cannot delete folder: E:\FRPAR\Home\fr10038\Symantec endpoint protection\SEP11.0.6\CentralQ\QConsole Job Name: FRPAR -> DELIN_Home 
5/6/2015 10:33:02 PM Cannot delete folder: E:\FRPAR\Home\fr10038\Symantec endpoint protection\SEP11.0.6\CentralQ Job Name: FRPAR -> DELIN_Home 

$logText = Get-Content C:\logfileA
$regPatMessages="^([0-9\/]{8,10}\s?[0-9:.]{5,8}\s{1}[AMP]{0,2}\s?).*$"
$messages=$($logFile-imatch$regPatMessages)   

#I get the result I expected.

However I would like to use:

$regExMessages=[System.Text.RegularExpressions.Regex]"(?i)^([0-9\/]{8,10}\s?[0-9:.]{5,8}\s{1}[AMP]{0,2}\s?).*$"
$messages=$regExMessages.Matches($logFile).Value

#Here, I get no any result. - Why? I tried to add (?m) and or (?s) but still nothing ... ?

Second example:

$logFilePartB (all separated lines)
Files Added:      547  (824.94 MB)
Items Updated:    15  (8.84 GB)
Items Deleted:    13  (2.52 MB)

It get the result I like if I use -match:

$regPatFilesAdded="(?<=Files Added:\s+)[0-9][\\:_$-\.\f\t\w() ]+"$filesAdded=$($logFile-imatch$regPatFilesAdded).Replace("Files Added:","").Trim()

If I use the [System.Text.RegularExpressions.Regex] I will get this and all other lines below.
Why?

How can I get the results I expected with [System.Text.RegularExpressions.Regex]?

Thanks in advance

Ruben


Powershell to replace content in a file with HTML tags.

$
0
0
I have a file where I am trying to use PowerShell to replace the text in a file. This text happens to be inside of an HTML tag and I am unsure of how to replace the text within this tag. I am new to PowerShell so any help is greatly appreciated.

Ayuda para concatenar instrucción

$
0
0

1.- Add-MailboxPermission -Identityuser@bu.com.co -User jnavas -AccessRights FullAccess

2.- Export-Mailbox –Identity user@bu.com.co -PSTFolderPath c:\user.pst

 

La idea es leer los nombres de usuario de un archivo de texto plano, correr el script 1 y 2 en un solo script.

Powershell script running as Scheduled Task not able to get the Window of a process

$
0
0

Hi all,

I need Powershell to check for the main window opened by an existing process with a given process ID. I used the following command to do so:-

$title = (Get-Process -Id $processId).MainWindowTitle

I tested this by manually invoking it using Powershell and Powershell ISE, and it works great in both.

However when I set this to run as a Scheduled Task using the same parameters, the script is able to detect the presence of the process. However it returns blank for MainWindowTitle. 

The process I'm tracking is NOT the explorer.exe. Clarifying this because I researched that there is some oddities when it comes to detecting windows opened by this process. I'm detecting the process for Windows Photo Editor.

Anyone has any ideas why this is so? Is there any other ways to successfully do this? 

Thanks in advance for any suggestions!


PowerShell add the ADuser to ADGroup. How can i do that.

$
0
0

Hallo,

I have ADOrganizationalUnit, ADGroup and the ADUser. Now I will add the User to ADgroup. How I can do that.
I need command that the ADuser can adding to ADgroup.

ADOrganizationalUnit Test2
ADGroup schoolold
ADUser 1920817902

The script
New-ADOrganizationalUnit Test2

$rootDN = (Get-ADDomain).DistinguishedName
    New-ADGroup -Path "OU=Test2,$rootDN" -Name "schoolold" -GroupScope DomainLocal -GroupCategory Distribution


Import-CSV ".\Project W2k8-Server AD - Gebruikers2.csv" | Select-Object Roepnaam,Achternaam,tussenvoeg,Persoonsnummer,Functie,E-mail,Indienst ,`
    @{name='name';expression={$_.'Persoonsnummer'}},`
    @{name='EmailAddress';expression={$_.'E-mail'}},`
    @{name='profilePath';expression={'\\COMLIGHT\school\'+ $_.'Persoonsnummer' + '\'}},`
    @{name='userPrincipalName';expression={$_.'Persoonsnummer' + '@drachten.local'}},`
    @{name='sAMAccountName';expression={$_.'Persoonsnummer'}},`
    @{name='givenName';expression={$_.'Roepnaam'}},`
    @{name='surname';expression={$_.'tussenvoeg'+' '+$_.'Achternaam'}},`
    @{name='displayName';expression={$_.'Roepnaam'+' '+$_.'Achternaam'}},`
    @{name='department';expression={$_.'Functie'}},`
    @{name='description';expression={$_.'Indienst'}},`
    @{name='path';expression={'OU=Test2,DC=drachten,DC=local'}} |
    New-ADUser -ChangePasswordAtLogon $True -Enabled $True -AccountPassword $(ConvertTo-SecureString "Qwerty1" -AsplainText -Force)

Project W2k8-Server AD - Gebruikers2.csv
Roepnaam,Achternaam,tussenvoeg,Persoonsnummer,Functie,E-mail,Indienst,
Laurens,Post,,1920817902,Productie medewerker,xx@newwave.nl,8/1/2008, 

get list of vms ips ,dns, dg etc...

$
0
0

I need to find a the dns settings on a list of vms in a text file

$myvms = get-content .\myvms.txt

foreach ($vms in $myvms) 

 gwmi win32_networkadapterconfiguration -Filter ipenabled=true -ComputerName $vms |  ft -Property dnshostname, ipaddress, dnsserversearchorder, macaddress | ft -auto 

}

but the output is not what I want

its gives each line like this

dnshostname                   ipaddress                     dnsserversearchorder          macaddress
-----------                   ---------                     --------------------          ----------
drhpdigital                   {10.245.1.11}                 {10.50.1.56, 10.245.1.14}     00:50:56:B1:13:CF



dnshostname                   ipaddress                     dnsserversearchorder          macaddress
-----------                   ---------                     --------------------          ----------
VIEW-WIN7-001                 {10.245.10.41}                {10.245.1.4, 10.245.1.28, ... 00:50:56:9F:3F:2B

how do I output like this

dnshostname                   ipaddress                     dnsserversearchorder          macaddress

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

drhpdigital                   {10.245.1.11}                 {10.50.1.56, 10.245.1.14}     00:50:56:B1:13:CF

VIEW-WIN7-001                 {10.245.10.41}                {10.245.1.4, 10.245.1.28, ... 00:50:56:9F:3F:2B

instead?

of is there bettter way to do this?

thank you


cannot resolve tfsbuildextensions.activities.FileSystem

$
0
0

Hello All,

I am getting this warning on the TFS Build defenition.

cannot resolve tfsbuildextensions.activities.FileSystem

cannot resolve tfsbuildextensions.activities.Framework.

The build steps are shown in Red color too.

Even if the Build defenition is executing those steps without any issues, on the design mode its not showing up.

TFS 2013 and Visual Studio Ultimate 2013.

Regards,

Anupama

Help with Powershell script comparing two folders

$
0
0

Here is my powershell script

$fs1 = Get-ChildItem -Recurse -path "C:\diff\left"

$fs2 = Get-ChildItem -Recurse -path "C:\diff\right"

Compare-Object -ReferenceObject $fs1 -DifferenceObject $fs2  >c:\compare\diff.txt

If ($fs1 -notmatch $fs2) {Write-Host "Error"}

If ($fs1 -match $fs2) {Write-Host "Success"}

Now the script works, I get the correct output in the text file. But My If statements do not work if there is more than a couple files in the folders. It will constantly return error despite the fact the folder contents are identical. I tried different comparison operators (eq, ne, etc) but these are the only ones I found that work.

I need two outputs, The one is the file that gets created that lists the files that different. The second part, the IF statements, is needed to return a success or fail to be used by a monitoring program to create an alert if they are not equal.

Any thoughts on how to clean up the If statements to get the right result?

How to match AD Computer Objects to OU container FOREACH-OBJECT or FOREACH

$
0
0

Trying to find away to MATCH or MOVE AD Computers with the number for a name example 6-CUNIOP123  with OU container with 006-SALES container .. Using powershell foreach-object found match it with the correct container .... Maybe even move computer to the correct container... Thank you all in advance

$RANGE = 1..10
$OUT1 = $RANGE  | ForEach-Object {Get-ADComputer -Filter "Name -like '$_*'"  -SearchBase "OU=InstructComputers,OU=Instructional,DC=episd,DC=org"}
$OUT2 = $RANGE  | ForEach-Object {Get-ADOrganizationalUnit -Filter "Name -like '00$_*'"  -SearchBase "OU=Instructional,DC=episd,DC=org"}
echo ($OUT1 | Select-Object DistinguishedName) ($OUT2 | Select-Object DistinguishedName)

Viewing all 21975 articles
Browse latest View live