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

Use Excel file records to traverse through IP addresses and look for events at the same timestamp

$
0
0

> I have an excel sheet with OU, Source network address and timestamp unique records.
> I would like to use the CSV file to read data and would like to go to each IP/source network address and fetch data from the event viewer for event id 4624 in Security logs that occurred at the same time stamp corresponding to that IP address.
> I would also like to detect the OS on the IP address and look for event id as per the OS. Windows server 2003 it is event id 540 and for Windows 2008 onwards it is event 4624
> I would like a powershell script using Get-winevent and Filter XML. If an IP address is not reachable it should go to the next IP and mention not reachable.
> I have a the following script which gives me errors. 

PLEASE HELP!!


$logFile = 'C:\test\test.csv'
$myOU = "OU=ABC,dc=contosso,DC=com"
$Computer = "Server1"
$logontype = @{ # LogonType as per technet
    2 = "Interactive" 
    3 = "Network"
    4 = "Batch"
    5 = "Service"
    7 = "Unlock"
    8 = "NetworkCleartext"
    9 = "NewCredentials"
    10 = "RemoteInteractive"
    11 = "CachedInteractive"
}

$time = import-csv -path C:\test\Results.csv | select-object timecreated
$OU = import-csv -path C:\test\Results.csv | select-object OU
$data = import-csv -path C:\test\Results.csv | select-object sourcenetworkaddress
ForEach ($server in $data)
{
 Get-WinEvent -FilterXml "<QueryList><Query Id=""0"" Path=""Security""><Select Path=""Security"">*[System[EventID=4624 and TimeCreated -eq [$time]]]</Select><Suppress Path=""Security"">*[EventData[Data[@Name=""SubjectLogonId""]=""0x0"" or Data[@Name=""TargetDomainName""]=""NT AUTHORITY"" or Data[@Name=""TargetDomainName""]=""Window Manager""]]</Suppress></Query></QueryList>" -ComputerName $Server | 
 ForEach-Object {
        $Event = $_ | select *
        $curOU = ([ADSI]"LDAP://<SID=$(($Event.Properties[4]).Value.Value)>").distinguishedName # TargetUserSid
        If (( $curOU -like $OU" ) -AND (($logontype[ [int] $Event.Properties[8].Value ]) -like "Interactive")) {{
            $Props = @{ 
                OU = $curOU.ToString();
                LogonType = $logontype[ [int] $Event.Properties[8].Value ];
                TimeCreated = $Event.TimeCreated;
                SourceNetworkAddress = $Event.Properties[18].Value
            }
            $LogonRecord = New-Object -TypeName psobject -Property $Props
            $Result += $LogonRecord
                    } 
    } 



$Result | Export-Csv -Path $logFile -append -UseCulture -NoTypeInformation # Log it to CSV

  

Variable reference

$
0
0

Hi,

I need to pass to variable to one function. The first one contain a path and the second one is null at start but when the function will resolve, that variable will be populate with an array (as reading a text file will return an array. Actually the file is read correctly in the function but the variable $ListeManufacturiers is not populate.

$ScriptDir = split-path -parent $MyInvocation.MyCommand.Path

$FichierManufacturiers = "\_include\Manufacturiers.lib"
$pathcompletManufacturiers = Join-Path ($ScriptDir) $FichierManufacturiers
set-variable -name ListeManufacturiers -visibility public
LireManufacturiers ($pathcompletManufacturiers) ([ref]$ListeManufacturiers)

function LireManufacturiers ($L_pathcompletManufacturiers,[ref]$L_ListeManufacturiers)
{

$L_ListeManufacturiers = Get-Content -path $L_pathcompletManufacturiers
if( -not $?)
 {
 [System.Windows.Forms.MessageBox]::Show("Problème dans l'importation de la librairie Manufacturiers.lib")
 Exit
 }
}

Why?

François Racine

Unable to find CMS Groups Path with SQLPS

$
0
0

I'm starting to mix CMS and SQLPS so as an experiment I've registered a couple of groups on my local instance (defined as CMS) and I'm trying to list the groups (and eventually loop between the servers within each group).

So the first thing I want to do is list the ProductVersion of each server in one group with something like 'select SERVERPROPERTY(ProductVersion')'.

Scenario:

-Local Instance Registered as CMS.

-Defined Groups: TestServers, QAServers, ProdServers.

-I got like 10 servers on each group.

In a PS cosole I run this to Import the sqlps module:

Import-Module sqlps -DisableNameChecking

After that I try to test the path for one of my CMS group and I get "False" value.

Not sure I'm this is a sintaxis error or I should be doing anything else before I can get to the servergroup path:

test-path -path "SQLSERVER:\SQLRegistration\Central Management Server Group\<ComputerName>\testservers\"

I've also tried the following:

test-path -path "SQLSERVER:\SQLRegistration\Central Management Server Group\testservers\"

With the same result.

These are my first steps in PS so probably there's much learning to do, so if anyone can point me on the right path I'll appreciate it.

Thank you

chunking up an array then using jobs, help testing

$
0
0

Hi all, i am having trouble testing this out, basicaly i have a big array of citrix sessions that i want to send messages to, so i chunk that array into 80, leaves me with about 100 sessions per, i think the chunking is workng fine its the jobs i am not sure if its running through all of them... I just want to make sure if 8000 variables are going in, it runs through 8000 variables and performs the operation

Code:

Add-PSSnapin Citrix.XenApp.Commands -ErrorAction SilentlyContinue
$env = "test"
$all = get-xasession -BrowserName $env | ? {($_.state -ne "listening") -and ($_.sessionname -ne "console")}
#split the list
$n = 80
$chunks = @{}
$count = 0
$all |% {$chunks[$count % $n] += @($_);$count++}
0..($n-1) |% {
start-job -scriptblock {
    ForEach ($session in $args){
    Add-PSSnapin Citrix.XenApp.Commands -ErrorAction SilentlyContinue
    Send-XASessionMessage -SessionId $session.SessionId -ServerName $session.ServerName -MessageTitle "Message from Citrix Admin" -MessageBody "test"
}
} -ArgumentList $chunks[$_] > $null
}

Could someone take a look and run a possible test?

Thanks

Use powershell to Download/Install SCCM approved updates and not reboot

$
0
0

Hello,

I am looking for some Powershell method to interact with Microsoft Update in a System Center Configuration Manager 2012 R2 environment but not use an already existing Module, Function on remote servers.  Hopefully without using WinRM.

For example, a server01 is out of Patch Compliance.  Run powershell script to fix common problems.  Then run 2nd powershell script to instruct Microsoft Update agent to download/install patches but not restart.

Hopefully this can be down some what easily in Powershell.  I tried looking for anything to get me started down this path but thus far have only found existing scripts/modules and functions.

Thanks in advance!

How to tail log files from particular string

$
0
0

Hello,

We would like to tail several log files "live" in powershell for particular string. We have tried to use "get-content" command but without luck because everytime as a result we received only results from one file. I assume that it was caused by "-wait" parameter. If there is any other way to tail multiple files ?

Our sample script below

dir d:\test\*.txt -include *.txt | Get-Content -Wait | select-string "windows" |ForEach-Object {Write-EventLog -LogName Application -Source "Application error" -EntryType information -EventId 999 -Message $_}

Any help will be appreciated.


Mac


Get-ACL Error Continuation and Server List

$
0
0

Hi All,

I'm conducting an audit of all folders on network shares that are spread accross several servers.  I'm very new to PS but from my research I have put together the following:

Get-ChildItem \\server\share -Recurse | Where-Object{($_.psiscontainer)} | Get-Acl | select-object path -expandproperty access | Export-CSV results.csv

This has been working ok but I hit an 'unauthrosied operation' error when it trys a folder that I do not have permissions to (i'm running as domain admin).  That's fine but it's a termination error which I can't seem to work around.  I have tried things like -ErrorAction SilentlyContinue but it just stops without producing the error and will not continue.  I have also tried a try and catch which I found on Technet but can't seem to get the -recurse to work:

$fse = Get-ChildItem \\server\share -recurse | Where-Object{($_.psiscontainer)}
$fse | %{$f=$_; try { get-acl $_.FullName } catch { Write-Warning "Failed to access $($f.FullName)" }}

I've tried my best to get the code to continue after the error but I just can't see what I am doing wrong.  Any ideas?

Also, I have many many shares to test which are all listed in a spreadsheet.  I'm been trying to research how I can use this spreadsheet instead of writing in the server and share for every one I want to test.  However this is now going way above my head and I can't get anywhere near to a semi-working example.  Is there a way I can use the above to reference a spreadsheet and test each share that is listed?

Many Thanks.

Break from loops

$
0
0

I have a Loop2 inside Loop1. What command can be used to replace 'GOTO Loop1'  to continue Loop1 without executing command3 and command4 when If condition is met?

1..10 | % { # Loop 1

         command1

         command2

         array1, array2, array3 | % { # Loop2

              If ( $_ -contains 'abc' ) { GOTO Loop1 }

         }

         command3

         command4

}



Best resources to learn PowerShell

$
0
0
Could you share the Best resources to learn PowerShell

Internet Explorer COM Automation Not Working

$
0
0

I've been searching for a solution to this for a while and I'm stunned and embarrassed I haven't found more helpful pages with information how to solve this problem for myself.

I have a few different scripts that spawn an instance of IE, navigate to the page, then update and click elements.  They work fine with IE 8, but nothing newer.  

$ie = New-Object -comobject InternetExplorer.Application
$ie.Visible = $true
$ie.Navigate($URL)


This works fine.  I can type $ie.document | gm at the console and see getElementById, getElementsByClassName, etc in the list of methods and properties, but if I try to access them I get an error:

Cannot find an overload for "getElementsByClassName" and the argument count: "1".
At line:1 char:36
+ $ie.document.getElementsByClassName <<<< ("input")
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

I found this link:

http://stackoverflow.com/questions/17924770/how-can-i-translate-or-run-a-vbscript-function-inside-a-ps1-file

That gets me a little bit further:

$EmailField = [System.__ComObject].InvokeMember("getElementsByClassName",[System.Reflection.BindingFlags]::InvokeMethod, $null, $ie.document,"email")


If I output $EmailField I get a long list of properties that includes:

type                         : email
value                        :
name                         : email

But when I try to edit $EmailField, I get another error:

PS C:\Users\user> $EmailField.value
PS C:\Users\user> $EmailField.type
PS C:\Users\user> $EmailField.name
PS C:\Users\user> $EmailField.value = "email@email.com"
Property 'value' cannot be found on this object; make sure it exists and is settable.
At line:1 char:13
+ $EmailField. <<<< value = "email@email.com"
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : PropertyAssignmentException

Also from the previous site I tried using the similar method as above:

[System.__ComObject].InvokeMember("value",[System.Reflection.BindingFlags]::SetProperty,$null,$EmailField,"email@email.com")


But that caused another error:

Exception calling "InvokeMember" with "5" argument(s): "Unknown name. (Exception from HRESULT: 0x80020006 (DISP_E_UNKNO
WNNAME))"
At line:1 char:34
+ [System.__ComObject].InvokeMember <<<< ("value",[System.Reflection.BindingFlags]::SetProperty,$null,$EmailField,"emai
l@email.com")
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

I found another link that mentioned a missing microsoft.mshtml.dll and related it to this problem with IE without Office installed, which I can't find now, but copying that file and loading it didn't make any difference in the behavior.

I can't believe I'm the only one having this problem...anyone have an idea how I can access the IE Com object on newer versions? 


I hope this post has helped!

disabling password complexity via powershell

$
0
0

hi friends

i spent lots of time searching entire internet to find a command or script (powershell, cmd, VB, registry...) to be able to disable password complexity. there are few solutions which none of them works.

i wonder how what a pity if we can't do such simple thing in Microsoft windows

i really need that because i have created a script which contains many lines which automates windows customization which i always need in my classrooms for testing & teaching purposes

thanks for any help

using a variable in netsh command to set ip address on NIC

$
0
0

hi friends

i wrote an script which gets an input & use that variable to set ip address on NIC. but actually it doesn't set ip address. may you please help me.

my script contains:

$VMNumber=Read-Host "please enter your VM number (for example 2)"

Netsh interface ipv4 set address NIC static 192.168.1.$VMNumber

Identical commands return different object types.

$
0
0

I'm currently working on a script which will query an SQL database for some information. I've written the commands to run a query against a database as below:

# Open the SQL connection
$Connection.Open()

# Create and execute the T-SQL query
$Command = $Connection.CreateCommand()
$Command.CommandText = "SELECT * FROM SCCM_Migration.dbo.MigrationInfo"
$FirstResult = $Command.ExecuteReader()

# Close the SQL connection
$Connection.Close()

The $Result object is a DataReader object which in turn can be used in combination with the a DataTable (System.Data.DataTable) object.

After checking the above commands I decided to put it together in a function (see below) for ease of use.

Function Run-SQLQuery {
    param(
        [System.Data.Common.DbConnection]$Connection,
        $Query
    )
    If ($Connection.State -ne "Open") { $Connection.Open() }

    $Command = $Connection.CreateCommand()
    $Command.CommandText = $Query.ToString()
    $Result = $Command.ExecuteReader()

    Return $Result
}
I've used this function in the following command line:
# Define query
$Query = "SELECT * FROM MyDatabase.dbo.DatabaseTable"

# Use the function
$SecondResult = Run-SQLQuery -Connection $Connection -Query $Query

The biig problem here is that the object returned by the function is of type DataRecordInternal which can't be used with the DataTable class.

Can someone shed some light on the reason why the function returns a different type than the separate command lines?

creating a code snippet for Where-object block in PS 4.0 ISE

$
0
0

hi friends

i am getting crazy with creating a code snippet for the  Where | {$_.company -match "google"}in PS 4.0 ISE.

i have tried many commands but each time i got error   :-(

New-ISESnippet -title Mysnippet -Description test -text "Where | {$_.company -match "google"}

really get tired. also nothing found after lots of googling



How to replace every letter not enclosed in a pair of double quotes with lowercase?

$
0
0

I need to change regular expression in this line of code:

[regex]::replace('TEST"TEST"TEST', '(["])(.*?)(\1)', {$args | foreach {$_.Value.ToLower()}}, 'IgnoreCase')

Currently it matches everything between " quotes but I need opposite effect.

Also is there a way to modify that regex to allow nested qoutes?


Insert delimiters

$
0
0

Hi,

I tried to insert Pipe-Delimiters at positions in text file, but i get this error, please some can help sort it.

$path ="c:\bkps\sample.txt"
$Positions=@(2,9,16,32)
$dat = Get-Content $path
$Positions | foreach {$dat
$dat=$dat.Insert($_,'|')
}
$dat > $path


Method invocation failed because [System.Object[]] doesn't contain a method named 'Insert'.
At line:5 char:17+ $dat=$dat.Insert <<<< ($_,'|')+ CategoryInfo          : InvalidOperation: (Insert:String) [], RuntimeException+ FullyQualifiedErrorId : MethodNotFound




Locate all possible gateways in network

$
0
0

Using Powershell 4.0. I want to know if there is a way to locate all possible gateway by IP in our network? We have multiple global sites but only interested in locating the gateways....

I'm assuming by querying our DHCP servers we can locate the gateways.....

Thanks!


Not recognise as a cmdlet??

$
0
0

Hi,

Sometimes that function will be call and sometimes not. The program just pass over it with a "LireConstantes" not recognise as a cmd-let. Thats strange...

$ScriptDir = split-path -parent $MyInvocation.MyCommand.Path
$FichierdeConfiguration = "\_include\Constants.ps1"
$pathcompletconfig = Join-Path ($ScriptDir) $FichierdeConfiguration

LireConstantes $pathcompletconfig

function LireConstantes
{
. $pathcompletconfig #Dotsourcing

Any idea?

Thanks,

François

Invoke-SQLCmd2 truncating VARCHAR field

$
0
0

I have a table with a field called output_field as VARCHAR(max)

I am using the Invoke-SQLCmd2 - I got no error but the field output_field is being truncated at 117 position...need help.  This field should not no longer than 500 chars.

here is my code...

function Invoke-Sqlcmd2
{
   
[CmdletBinding()]
    param(
    [Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance,
    [Parameter(Position=1, Mandatory=$false)] [string]$Database,
    [Parameter(Position=2, Mandatory=$false)] [string]$Query,
    [Parameter(Position=3, Mandatory=$false)] [string]$Username,
    [Parameter(Position=4, Mandatory=$false)] [string]$Password,
    [Parameter(Position=5, Mandatory=$false)] [Int32]$QueryTimeout=60000,
    [Parameter(Position=6, Mandatory=$false)] [Int32]$ConnectionTimeout=60000,
    [Parameter(Position=7, Mandatory=$false)] [ValidateScript({test-path $_})] [string]$InputFile,
    [Parameter(Position=8, Mandatory=$false)] [ValidateSet("DataSet", "DataTable", "DataRow")] [string]$As="DataRow"
    )

    if ($InputFile)
    {
        $filePath = $(resolve-path $InputFile).path
        $Query =  [System.IO.File]::ReadAllText("$filePath")
    }
 
    $conn=new-object System.Data.SqlClient.SQLConnection
      
    if ($Username)
    { $ConnectionString = "Server={0};Database={1};User ID={2};Password={3};Trusted_Connection=False;Connect Timeout=60000;" -f $ServerInstance,$Database,$Username,$Password,$ConnectionTimeout }
    else
    { $ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout=60000" -f $ServerInstance,$Database,$ConnectionTimeout }
 
    $conn.ConnectionString=$ConnectionString
     
    #Following EventHandler is used for PRINT and RAISERROR T-SQL statements. Executed when -Verbose parameter specified by caller
    if ($PSBoundParameters.Verbose)
    {
        $conn.FireInfoMessageEventOnUserErrors=$true
        $handler = [System.Data.SqlClient.SqlInfoMessageEventHandler] {Write-Verbose "$($_)"}
        $conn.add_InfoMessage($handler)
    }
     
    $conn.Open()
    $cmd=new-object system.Data.SqlClient.SqlCommand($Query,$conn)
    $cmd.CommandTimeout=60000
    $ds=New-Object system.Data.DataSet
    $da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd)
    [void]$da.fill($ds)
    $conn.Close()
    switch ($As)
    {
        'DataSet'   { Write-Output ($ds) }
        'DataTable' { Write-Output ($ds.Tables) }
        'DataRow'   { Write-Output ($ds.Tables[0]) }
    }
 
} #Invoke-Sqlcmd2

...

$query="select output_field from dbo.HST_OUTPUT_TBL WHERE LOG_ID = $LOG_id"

Invoke-SQLCmd2 -ServerInstance $sqlserver -Database $dbname -Query $query | Out-File $OUTTMP

here is the sample of whats truncation look like...

999999|XX||XXXXXX| |XXXXXXXXXXXX|XXXXXXXXXXXXXXXXXXXX|XXXXXXXXXXXXXXXXXX|XXXXXXXXXXX|XX|XXXXXXXXX||||||||||||||||888...

it was truncated and leave the "..." at the end.

Appreciate any suggestion


PS script file works differently when scheduled vs run from Powershell

$
0
0

The following script works when run from PowerShell window.

The script does not work when ran as scheduled task.   The email part works fine, however the body is blank.    It also does not update the timeran.txt file.

MORE INFO ADDED:     the script is scheduled on the Hyper-V host box.  user is Domain Administrator equivalent.     OS is server w2k12.     TASK  CONFIG:   user is domain\Adminequivalent.    Run whether user is logged in or not.      trigger is 7:00 AM.     Action is   Powershell        argument is  .\scriptname.ps1      Start in  is   C:\scripts

TIA..   bob

# Variables
 $filedate = get-date
 $computer = gc env:computername
 $FromEmail = "myemail@mydomain.com"
 $ToEmail = "myemail@mydomain.com"
 
 # Establish Connection to SMTP server
 $smtpServer = "mail.mydomain.com"
 $smtp = new-object Net.Mail.SmtpClient($smtpServer)

  get-date | Out-File  "C:\Util\timeran.txt" -append

  Measure-VMReplication -ComputerName Hyp-03 | Select Name,Health,LreplTime | ConvertTo-Html | Out-File "C:\Util\report.html"

  $a = Get-Content C:\Util\report.html

#  email  
 $email = new-object Net.Mail.MailMessage
 $email.Subject = "$($computer) Replication Report: $($filedate)"
 $email.From = new-object Net.Mail.MailAddress($FromEmail)
 $email.Sender = new-object Net.Mail.MailAddress($FromEmail)
 $email.IsBodyHtml = $true
 $email.Body = $a
 $email.To.Add($ToEmail)
 
 # Send Email
 $smtp.Send($email)


Bob Lee




Viewing all 21975 articles
Browse latest View live