Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all 15028 articles
Browse latest View live

login failed attempt powershell script

$
0
0

Hi Guys,

I need your help. I need powershell script to get login attempt report into csv file. is there any script ?

Thanks in advanced 

I have made this script but i don't know where and what am i missing in this script, It is not working:-



#>

Param(
    [array]$ServersToQuery = (hostname),
    [datetime]$StartTime = "January 1, 1970"
)

    foreach ($Server in $ServersToQuery) {

        $LogFilter = @{
            LogName = 'Security'
            ID = 4625, 644, 681, 529
            StartTime = $StartTime
            }

        $AllEntries = Get-WinEvent -LogName "Security" -FilterHashtable $LogFilter -ComputerName $Server

        $AllEntries | Foreach { 
            $entry = [xml]$_.ToXml()
            [array]$Output += New-Object PSObject -Property @{
                TimeCreated = $_.TimeCreated
                Computer = $entry.Event.EventData.SubjectUserName
                User = $entry.Event.EventData.TargetDomainName
                logontype = $entry.Event.EventData.LogonType
                IPAddress = $entry.Event.EventData.IpAddress
                EventID = $entry.Event.System.EventID
                ServerName = $Server
                }       
            } 

    }

    $FilteredOutput += $Output | Select TimeCreated, Computer, User, logontype, IPAddress, ServerName @{Name='Action';Expression={
                if ($_.EventID -eq '4625'){"Unknown user name or Bad password"}
                if ($_.EventID -eq '529'){"Unknown user name or Bad password"}
                if ($_.EventID -eq '644'){"User Account Locked Out"}
                if ($_.EventID -eq '681'){"The logon to account: %2 by: %1 from workstation: %3 failed"}
                }
            }

    $FilePath = "$env:C:\RDP_Report.csv"
    $FilteredOutput | Sort TimeCreated | Export-Csv $FilePath -NoTypeInformation

Write-host "Writing File: $FilePath" -ForegroundColor Cyan
Write-host "Done!" -ForegroundColor Cyan


#End

When i run this script it is giving following error:-

I am not good in powershell. it is just copy from another script, and edit the event log and other information.

Original script is here :-

https://gallery.technet.microsoft.com/scriptcenter/Remote-Desktop-Connection-3fe225cd


Preserve line breaks in textbox

$
0
0

Hi Guys,

 This is probably something that is very simple to do, but how to we get PowerShell to preserve line breaks for text typed into PowerShell textboxes?

Thanks

output of the script - syntax prob

$
0
0

Hi,

I found a script for user logoff...

______What we do is, create a scheduled task running as system account. It uses a batch that goes:

del %temp%\DisconSessions.txtdel %temp%\delSessions.txtqwinsta |findstr Disc >%temp%\DisconSessions.txtfindstr /v services %temp%\DisconSessions.txt>%temp%\delSessions.txtfor /f "tokens=2" %%a in (%temp%\delSessions.txt) do logoff %%a

_____________

I created a batch...

When run for test from cmd (on Win10),nothing happens and I see one % is missing in last line output.

So, it looks like that:

for /f "tokens=2" %a in (%temp%\delSessions.txt) do logoff %a

Is this script for bat? (was not mentioned in the page I found. Or something else?

thx.


--- When you hit a wrong note its the next note that makes it good or bad. --- Miles Davis

Functions - Data Manipulation question

$
0
0

I'm creating an activity in SCORCH and I need to create a function.

I'm having trouble creating an activity to extract a service display name from a SCOM alert description.

I think I know the activity I need to use, but I can't seem to figure out the correct function to write to extract the service name from the SCOM alert description field.

in our alert description field it reads this: (no quotes in the alert field)

"The following service is down on server ABCD.com : <service display name>"

For example: "The following service is down on server ABCD.com : Print Spooler"

I need to have a function that extracts everything AFTER the ": " (colon and space) and passes on the service display name to my next activity.

Thank you for your help with this!

PCSystemType on Remote Computers

$
0
0

I am extremely lucky to go through a MS Audit and they are asking me how many laptops/desktops are on the domain. I am trying to pull this data from PS but have no luck so far. Could anyone assist me on my ignorance?

Here are some things I have tried.

$Computers = Get-ADComputer -Filter * | Select Name		   
foreach($comp in $computers)
	{
		Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName $comp
	}

$ou = [ADSI]"LDAP://domainname.com CN=computers,DC=domainname,DC=com"
$computers = $ou.PSBase.Get_Children()
$arrInfo = @()
foreach($node in $computers) 
	{
		$arrInfo += Get-WmiObject -query "Select Name,Manufacturer,Model, NumberOfProcessors, TotalPhysicalMemory, PCSystemType From Win32_ComputerSystem" -computername $node.Name  
	}
$arrInfo | format-table Name, Manufacturer, `
           Model, NumberOfProcessors, TotalPhysicalMemory,PCSystemType

$Computers = Get-ADComputer -Filter * | Select Name
$arrInfo = @()

foreach ($node in $Computers) 
	{
		$arrInfo += Get-WmiObject -query "Select Name,Manufacturer,Model,PCSystemType From Win32_ComputerSystem" 
		-ComputerName $node.name
	}
$arrInfo | FT Name, Manufacturer, Model,PCSystemType
Any help would greatly be appreciated, thank you!

How to detect if drive is fully encrypted or used space only encrypted?

$
0
0

When a drive is 100% encrypted then the below will return 100 as in 100% encrypted:

$EncryptionData= Get-WmiObject -Namespace ROOT\CIMV2\Security\Microsoftvolumeencryption -Class Win32_encryptablevolume -Filter "DriveLetter = 'c:'"

$EncryptionData.GetConversionStatus().EncryptionPercentage

... but there seems to be no way to determine (programmatically) if the encryption is 'Used Disk Space Only'  or the full volume is encrypted.

Now I know that manage-bde -status "C:" will return the following if that is the case:

"...
    BitLocker Version:    2.0
    Conversion Status:    Used Space Only Encrypted
    Percentage Encrypted: 100.0%
..."

... but if not:

"...
    BitLocker Version:    2.0
    Conversion Status:    Fully Encrypted
    Percentage Encrypted: 100.0%

..."

... so clearly manage-bde is able to determine if the disk is Used space Only or not, but without parsing the output of the manage-bde command I can't see a way of programmatically determining whether an encrypted drive is full or Used space only.  (And parsing the output of manage-bde is problematic as if the encryption is in progress, it will not show if the disk is Used space only or full that is in progress, only that 'some encryption' is in progress).

I need to be able to drop a script on computers for reporting purposes to see the level of encryption, and whether it is used space or full disk. 

Many thanks for looking at this.
Darren.


Omit null properties of a powershell cmdlet query return

$
0
0

Hello,

I'm trying to parse the results of a cmdlet and was wondering if there is a way I could do it dynamically.

If you do a get-inboxrule and return all the properties, 50% are blank depending on the how complex the creation of the rule was.  All the rules will not be the same, so the fields would change.

Is there a way to save the results without creating an array of all the properties and then do a check on each one to see if there is a value?

IE:

$mbx = get-inboxrule -Mailbox test.mailbox@microsoft.com -identity "BigInboxRule"

#Get-inboxrule has a bunch of properties...  I want to #just filter out all the null ones and present only the #ones that have attributes.

#Am I stuck having to do something like this?
$properties = "isvalid","mailboxownerid","stopprocessingrules","redirectto","markasread" etc. etc.. until all properties for get-inboxrule are part of an array

$report = @()

foreach ($entry in $properties){
      if ($mbx.entry -eq $null){
          continue}
     else{
         $report += $mbx.entry}

Now, the example may not work, I just typed up a quick example, is this all that is available?  Or is that the hard way?  Any help is appreciated!


Win32_NetworkLoginProfile LastLogon - The results are incorrect in domain joined machines.

$
0
0

Greetings,

I am in need of calculating the time taken from Ctrl + Alt + Del to the Desktop\Explorer.

Based on multiple online posts, I have decided to use the Win32_NetworkLoginProfile and the property LastLogon - this works a treat on non-domain joined machines.

However, the domain joined machines somehow brings inaccurate\incorrect (an old LastLogon entry for the user) results often.

I would like to understand where Win32_NetworkLoginProfile pull data from. My assumption was that the data comes from the local machine that I am connecting to.

A link to the WMI class
https://msdn.microsoft.com/en-us/library/aa394221(v=vs.85).aspx

The few lines I am running to achieve the mentioned. (Ignore the warnings for existing event log source)

try{
    $Computer = hostname
    $LastLogon = $null
    $LastLogon = Get-WmiObject Win32_NetworkLoginProfile -ComputerName $Computer |
        Sort -Descending LastLogon |
        Select * -First 1 |
        ? {$_.LastLogon -match "(\d{14})"} |
            % {
                New-Object PSObject -Property @{
                    Name=$_.Name ;
                    LastLogon=[datetime]::ParseExact($matches[0], "yyyyMMddHHmmss", $null)
                }
            }
     $LogOnTime =  ((Get-Date).TimeOfDay.TotalSeconds) - $LastLogon.LastLogon.TimeOfDay.TotalSeconds
     $Message = "It has taken  " + (((Get-Date).TimeOfDay.TotalSeconds) - $LastLogon.LastLogon.TimeOfDay.TotalSeconds) + " seconds to load the Desktop from the time the credentials were entered by  " + $LastLogon.Name
     New-EventLog -Source "LogOnTime" -LogName Application
     Write-EventLog -LogName Application -Source "LogOnTime" -EntryType Information -EventId 12345 -Message $Message
     }
Catch
    {
    Write-EventLog -LogName Application -Source "LogOnTime" -EntryType Information -EventId 12345 -Message "Something went wrong!"
    }   

Thanking you in advance.

Bat Script sometimes does not run on startup

$
0
0

Hello everyone,

I've created a batch file that installs all the software we have here at our company. Since Windows 10 picks its own laptop name which mess up our process since we have a naming convention for our devices. I have to get the scripts to add it to the domain and change computer name, reset it then run the second part of the script, since some of our software need the computer name up to standard.

The issue arises where the sometimes the second script won't even run upon computer startup. The second script is run from Task Scheduler with highest privilege, I've set the auto sign in with the local admin username and password. 80% of the time it works fine. But there's a certain batch of computers that won't get script to run at all and I can't seem to find the pattern. All of these computers are Dell Windows 10 starting patch 1709 (idk why, we always have to run 1803 right afterward).

Is there a way to guarantee this script to run. I've had instances of some of our admin just let the script run, go to a meeting and come back 1 hour later just to realize that the second script did not run as intended. There's no history in TaskSched showing that the script is ever run.

General layout of script:

Initial script (Run from network drive): Download everything then run the 1st installation script.

1st script: Check if computer is win10, if so, change name add to domain create registry for auto-login then restart (if win7 proceed to installation and done)

2nd script: (Win10 only) Launched by Task Sched with highest priv, run all installations, put file where they suppose to be, delete registries then done. This is the script that has issue launching.

Thanks ahead!


Benedict Wolf

Script does not work across domain

$
0
0

Hi,,

I have  a script to check the list of account status in AD( whether it is exist or not ). But the script does not search account across the domain!

Can anyone help me to correct this, so that it runs across the domain  to see whether the account exist or not ?

Import-Module ActiveDirectory
$UserList = get-content C:\temp\Accounts.txt
Foreach ($Item in $UserList) {
$user = $null
$user =  Get-aduser -filter {samAccountName -eq $Item}
if ($user)
    {
    $user | Out-File C:\temp\existingAccounts.txt -encoding default -append
    }
    else
    {
    "$item does not exist" | Out-File C:\temp\NotExistingAccounts.txt -encoding default -append
    }
}

Scripting help to change a registry key value

$
0
0

Hello all,

I need help changing the value in a registry key.

The key in question is:

HKEY_CURRENT_USER\Software\SoftwareCompany\SoftwarePiece\Settings\COMPANY

The Value name is:

Script

And the Value Data needs to change from:

<none>

to

Default.scp

Any help would be great!

Updating lines in txt file by numbers

$
0
0

Hello,  I have a text file I need to update on occasion to re-number the end of specific lines.

I will receive a txt file that will have multiple segments,  and each segment needs to be uniquely numbered, and the start and stop of each segment needs to  match...  There will be a varying number of segments to renumber,  usually about 7 to 9 or so.. 

example.   a segment will start with:

     "  ST*835*00001 "
and ends with
     "  SE*123*00001 " 

The start line is always the same..  but the end line will vary by the numbers right after the SE*xxx"   and the file will have any number of lines between the start and end of the segment.

any suggestions on how to find each line (i'm having trouble finding the strings I think because of the " * ".  once I can find the lines, what would be  a good way to renumber them?

currently attempting to use the following, which I found on another page somewhere.

$FileContent = Get-Content "c:\temp\filename.txt"
$Matches = Select-String -inputObject $FileContent -pattern "ST*835*00001" -AlMatches
$Matches.Matches.Count

if I can find by the   "ST"   and the number at the end.. that is fine..  but how?

Powershell | Test-Path (to find missing files) in current running folder/subfolders

$
0
0

Hello,

I'm trying to create a script that does the following (attached bellow is the code I have so far):
-every time it runs from a different location (the script for example is manually copied in the root folder of a new location each time)
-the new location as the root folder of the script that is now running has sub-folders, and in one of them a sequence of files exist
-the script needs to check the last sequence number of the files and then count through all of them and verify that a number is not skipped from the sequence
-if it finds a sequence number not existing, report it

The structure of the folders are:  

    -root_folder
    --subfolder1
    ---capture_folder (including files that need to be verified as all present)
    --subfolder2
    ---capture_folder (including files that need to be verified as all present)

The filename structure is:   *_f_001r.* (subfolder1) and*_f_001v.* (subfolder2)

Here is were I am so far:

Write-Host "Missing files: "
$path = Get-ChildItem * -attributes D -recurse -include "capture"
$Last = [INT](Get-ChildItem -Path .\* -rec -filter *_f_*)[-1].BaseName.Substring(14,3)
$numbers = 1..$Last
foreach ($number in $numbers) {
if (Test-Path $path -Filter *$number*r*) { #Write-host "$number file exists"
}
else {Write-host "File $number r file does not exist" -ForegroundColor Red}
if (Test-Path $path -Filter *$number*v*) { #Write-host "$number file exists"
}
else {Write-host "File $number v file does not exist" -ForegroundColor Red}
}
Write-Host " "
Write-Host " "
Read-Host -Prompt "Press Enter to exit"

Any ideas? If I do something like $path = ".\*\*\*" it kind of works

Thank you,

D.


convert an event object (XML format) to text - Powershell

$
0
0

Hello

Look at this powershell piece of code:

$a = wevtutil qe System /q:"*[System/EventID=XXX]" /rd:true /c:1

do something 

echo $a > C:\Script\event.txt

The output is not so user friendly.

Nothing like the output of the following command:

wevtutil qe System /q:"*[System/EventID=XXX]" /rd:true /c:1 /f:text > C:\Script\event.txt
How can I "print" $a in this user friendly way?

Thank you and sorry for this silly question: I' new to powershell programming.

PowerShell: how to convert .msg (e-mail) files to .eml files

$
0
0

I would like to know if it's possible to convert .msg files into .eml files. I have a folder containing several .msg (mail) files but I need to convert them into .eml files. I would like to use PowerShell for this job, and I have taken a look at the System.Net.Mail.SMTPClient and System.Net.Mail.MailMessage objects, but so far i haven't found the solution for conversion .msg to .eml. Please help me out here.

Mark


PowerShell Convert Multiple Event Log Archives (evtx) to CSV files of the same size

$
0
0

Hi all,

Hoping someone can help me with this tricky one.

I have about 1 TB worth of Event Log Archives that I'm trying to convert to CSV. The resulting CSV files will then be ingested by an SQL Database.

The event log archives vary in size (due to trying to combine them, then splitting them for security reporting).

They range from 256 MB through to 20 GB. The initial attempts to combine logs from multiple servers were successful. They provided too large to be useful though and off the shelf Event Log tools wouldn't play nicely with evtx files bigger than 1 GB. Big mistake on my part, I know.

What I would like to do, using the most efficient method, is to read the events and parse them out as CSV files of the same size.

e.g. Log-001.evtx = 4 GB

Split Log-001.evtx to 400 x 100 MB CSV files

Log-002.evtx = 500 MB

Split Log-002.evtx to 5 x 100 MB CSV files.

I then hope to batch import these csv files (running over a week if needed, taking advantage of the Christmas break), and get SQL to ensure no duplicate events (same Server, Date & Time, Event ID, Event Message) are imported. I'm only concerned about duplicates because I want to process the big/merged log files just in case one of the originals was moved or missing.

I found a script that does this one at a time, and have tried using a couple of tools like Event Log Parser but it doesn't seem to take every column, just the 'highlights.'

I tried this:

$Logs = Get-ChildItem -Path 'c:\temp\logs\' -Recurse -Name *.evtx | Select-Object Directory,Name
foreach ($Log in $Logs)
    {
        $LogPath = Write-Host $Log.Directory
        $LogFileName = Write-Host $Log.Name
        $LogFullPath = Write-Host $LogPath + $LogFileName
        $CSVFileName = Write-Host $Log.Name+".csv"

        get-winevent -Path $LogFullPath | export-csv $CSVFileName -useculture
        exit
    }

It converts them, but takes an incredibly long time and still gives me massive CSV files. It also doesn't show me any progress, so I don't know if it has hung or where it is up to.

Any thoughts or suggestions would be greatly appreciated. Unfortunately I can't use off the shelf products as the only budgeted item I can use is my time :|

Thanks in advance and Happy Holidays,

Ian


Ian

Extract block text from large file text

$
0
0
Hi Team,
I am trying to extract the last text block from a text file...
Each block is separated by a line with "******"
Note that there are empty lines.

Example block:

quote

***************************************************

text

text

text

so on... (variable amount of lines)

unquote

Example full text file:

quote

***************************************************
text

text

text

so on... (variable amount of lines)

***************************************************

text

text

text

so on... (variable amount of lines)

***************************************************

text

text

text

so on... (variable amount of lines)

unquote

With this code I cant extract the last block counting lines from the end of the file... but sometimes is useless because the amount lines is variable.
Get-Content -Path $outlogfile -Tail 50 -OutVariable trim
So, the code must extract all text from the last separator line (**********************) until the end of file
Or delete all text above the last separator line (**********************)

Many thanks for your time!

Variables add to MSI installation help

$
0
0

Hi,

I am new to PowerShell. I am working on an install script that will install an MSI but I need to add some variables to the argument because it needs to be install on multiple computer from different servers. Here is the script I have written:

$IP=((ipconfig | findstr [0-9].\.)[0]).Split()[-1]
$IP2 = (([ipaddress]$ip).GetAddressBytes()[0..2] -join ".") + ".201"
$Hname = [System.Net.Dns]::gethostByAddress("$IP2").hostname
$Hname = $Hname.Substring(0,13
msiexec /i \\$Hname\Applications\DNA\DNAClient4.0.msi /l*v "C:\DNA40ClientInstall.log" INSTALLDIR="Q:\" DBNAME="PROD" EXEPATH="Q:\OSI\BANK\Exe" MAPPATH="\\$Hname\PROD" DELETE64BIT="True" /quiet
Start-sleep -s 100


Unable to set variable from each item in csv

$
0
0

Hi all,

I'm pretty stuck here.. I'm unable to associate a variable with my csv file. I import the csv which has three columns, UserPrincipalName, DisplayName, and NewUserPrincipalName. When I import the CSV attempt to associate the column UserPrincipalName and NewUserPrincipalName with a variable. 

Here is my script so far..

$csv = Import-csv"F:\temp\user.csv" -Header ("UserPrincipalName","DisplayName","NewUserPrincipalName")
ForEach($itemin$csv){
$UPN = $_.UserPrincipalName
$NewUPN = $_.NewUserPrincipalName
Set-MsolUserPrincipalName -UserPrincipalName$UPN -NewUserPrincipalName $NewUPN
}

i have this script for share and map printers but i need to change the print port!

$
0
0

hi, some body knows how to change print port using vbscript i want to change the print port from USB001 to USB002 when users performance logig, i have sevarals day looking this information on internet but i can't find it.

This is my script for sharing the print and map to lpt1 this for a old system

Dim objWMIService, objService
Dim strService,strComputer, PrintPortType, PrtName
PrtName = "TMUCASH"
PrintPortType = "USB"
strService="MpsSvc"
strComputer = "."
Set wshShell = CreateObject( "WScript.Shell" )
strComputerName = wshShell.ExpandEnvironmentStrings( "%COMPUTERNAME%" )
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

IF InStr(strComputerName,"CASH") THEN
IF printerExists("Generic / Text Only") THEN
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colInstalledPrinters =  objWMIService.ExecQuery("Select * from Win32_Printer Where Name = 'Generic / Text Only' AND PortName LIKE '%USB%'")

For Each objPrinter in colInstalledPrinters
 If objPrinter.Shared = False Then
     objPrinter.Shared = True
     objPrinter.ShareName = PrtName 
     On Error Resume Next
     objPrinter.Put_
     msg = Err.Description
     On Error GoTo 0
     If msg <> "" Then
        MsgBox "Cannot share " & objPrinter.Name & ": " & msg
     End If
 End If
Next

Set objShell = CreateObject("WScript.Shell")
strCmd = "net use lpt1 \\"& strComputerName & "\"& PrtName & " /persistent:yes /YES"
set objExec = objShell.Exec(strCmd)

Else

END IF
END IF

Function printerExists(str)
    printerExists = False
    Dim objWMIService
    Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
    Dim colPrinters
    Set colPrinters = objWMIService.ExecQuery("Select * from Win32_Printer Where Name = 'Generic / Text Only' AND PortName LIKE '%USB%'")
    Dim objPrinter
    For Each objPrinter In colPrinters
        If objPrinter.Name = str Then
            printerExists = True
            Exit For
        End If
    Next
End Function


Viewing all 15028 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>