Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all 6937 articles
Browse latest View live

Remove/Exclude the file path from the out-file or screen when doing a get-childitem recurse search

$
0
0

I created this command line to search all sub folders from where it is ran and use a certain file type and then do a select-string -pattern " the string you want"

Her is the script that has variables I use

get-childitem *snpdrvdbg*.log -recurse | select-string -pattern "$string" -context 3, 3 | Foreach {"$_$nl"} | out-file -Filepath $ActivityLog -encoding ascii

I am running this on a file share .  That path is \\stingray\data\2005436477\snap logs\SnapDrive.  This is actually a psdrive

Stingray                               FileSystem    \\stingray\data

 

The results that I get looks something like this in the txt file

\\stingray\data\2005436477\snap logs\SnapDrive\Snpdrvdbg.log:1727:01/12-12:08:36.480 PID:2464 TID:6976 filer_set.cpp@13  filer_t::get_network_name: start.
  \\stingray\data\2005436477\snap logs\SnapDrive\Snpdrvdbg.log:1728:01/12-12:08:36.480 PID:2464 TID:6976 localerror.cpp@82  Is_VDS_ITF_Error(): false.

I would like to know if it is possible to remove part of what is written to the txt file or shown on the screen like the current path I am in.  Looking to maybe see something like this:

Snpdrvdbg.log:1727:01/12-12:08:36.480 PID:2464 TID:6976 filer_set.cpp@13  filer_t::get_network_name: start.
Snpdrvdbg.log:1728:01/12-12:08:36.480 PID:2464 TID:6976 localerror.cpp@82  Is_VDS_ITF_Error(): false.

Now the file path will never be the same so I was trying to use a variable $path=$pwd.ProviderPath to reports back the current path and location I am in for example:

PS Stingray:\2005436477\snap logs\SnapDrive> $path=$pwd.ProviderPath
PS Stingray:\2005436477\snap logs\SnapDrive> $path
\\stingray\data\2005436477\snap logs\SnapDrive
PS Stingray:\2005436477\snap logs\SnapDrive>

Any help would be great as I am running out of brain cells here.

 

If you have any questions please feel free to reply.  I work 3rd shift so I am here most of the night to reply back in a timely manner.   Again thank you for who wver can help me.

Thanks

George


How do I get a log file...

$
0
0

Hi Guys,

I have a script which removes a folder from a number of servers, names of which are in a .ini file.

$VM_names = Get-Content "D:\Scripts\VMnames.ini"
ForEach ($VM in $VM_names){ Remove-Item "\\$VM\modules\foldername"  -Recurse -Force }

I'd like to create a log file which contains the name of the server and the date and time when it was done.

Any help would be much appreciated.

Cheers

 

 

Listing file name and file path (full path)

$
0
0

I have a list of files to be searched through a directory and sub directories. If the files if found within the folder structure i want it to be listed with full path.

How can i achieve with the powershell script please..

I tried something like this

Get-ChildItem -Recurse -Force $filePath -ErrorAction SilentlyContinue | Where-Object { ($_.PSIsContainer -eq $false) -and  ( $_.Name -like "*$fileName*") } | Select-Object Name,Directory | Out-File c:\temp\output.txt

i have two issue with above

it doesnt list the complete path.. it shows ... at the end

Not sure how I can loop through a list of files which I need to search through the directory if they exists.

Email the user after 5 days if the same user exists in log after 5 days

$
0
0

Hi All,

I have a script to get email and error from a logs. I'm planing to email the user using command send-mailmessage. But how can i make sure that I won't send out the same email within 5 days? because the system will auto generate the log and the user will keep receiving emails. I wanted to setup if the same user exists, no email will send out and after 5 days if the same user exists again, then send out the email.

 

Rgds,

Liew

 

Send Click and Keys to RDP session

$
0
0

I am trying to automate to RDP a computer and start a program. I am trying it with WASP from www codeplex

Ideally my aim is to -

RDP to a server and Click OK to Legal Notice window

Click on start menu > Run > Enter key

Type a command in run prompt and then send enter key

Here Stuck in sending keys to RDP session. Can anyone help me to make it work? If it’s not possible via PowerShell then what are my other options?

This is what I have so far..

$process = Start-Process -FilePath mstsc -PassThru
Start-Sleep -Seconds 2
$mstsc = Select-Window | Where-Object { $_.ProcessID -eq $process.Id }
$mstsc | Send-Keys Server.domain.com~

#Sleep to enter password
Sleep -Seconds 15

#Send enter key fails here
$mstsc | Send-Keys ~

I am a newbie please help and be nice this stuff is going over my head.

$
0
0
Hi all

Sorry for this but I am a newbie to scripting I need help with following powershell script

In AD i need to do the following

I have a container called Users, Under the users container I have Disabled Accounts, New Account, Others Accounts.

I need to pull last logon information from just the users conatiner, as I am not interested in the users in Disabled Accounts, New and other.

Is there a way to do this?

I have the following below but this pulls all user infromation from Users, Disabled Accounts, New Account, Others Accounts, but I only need the information from Users.

The below is what I have so far.

 

 

Import-Module ActiveDirectory

function Get-ADUsersLastLogon()

{

$dcs = Get-ADDomainController -Filter {Name -like "*"} $users = Get-ADUser -searchbase "OU=Users,DC=Test" -Filter * $time = 0 $exportFilePath = "c:\lastLogon.csv"

$columns = "name,username,datetime"

Out-File -filepath $exportFilePath -force -InputObject $columns

foreach($user in $users)

{

foreach($dc in $dcs)

                    {

$hostname = $dc.HostName

$currentUser = Get-ADUser $user.SamAccountName | Get-ADObject -Server $hostname -Properties lastLogon

 

if($currentUser.LastLogon -gt $time)

{

$time = $currentUser.LastLogon

}

}

$dt = [DateTime]::FromFileTime($time)

$row = $user.Name+","+$user.SamAccountName+","+$dt

Out-File -filepath $exportFilePath -append -noclobber -InputObject $row $time = 0 } } Get-ADUsersLastLogon

 

 

 

 

 

Any Help would be great.

Error overload for Add and data type issue

$
0
0

Hi All,

 

I'm currently make a wsus script but having issues with two things. Firstly, when trying to add a group to the ApprovedCOmputerTargetGroups with .Add($group) its displaying error overload for add. The $group is equal to "Company1" and return a string.

The last issue is when using the -eq operator having -eq $group causing the script to brake and when I place the value of $group along side -eq "Company1" it's works.

 

If anyone can give some ideas why these issue are accruing, this will be great.

 

Thanks,

Paul

Colour output in a script not working

$
0
0

Hi

I have this simple script that reads a file (list of servers) and pings it and outputs if pinging the word up in green is displayed next to server if or down red is displayed

My problem, say in this example there are 6 servers s1,s2....s6 and s3 is not pinging

I have found that

s1/s2 says up in green

s3 says down in red

s4-s6 says up but in red, this is my problem why is the reminder red.

any help would be really appreciate or even a nice way to format this

 

$MessageParams = @{
From = 'abc@test.com’
To = "recabc@test.com”
subject = "Ping Exchange”
SMTPServer = 'SMTPServer'
}
 
$report = ""
$ServerName = get-content “.\pinglist.txt”
         
    foreach ($Server in $ServerName)
    {
                if (test-Connection -ComputerName $Server -Count 1 -Quiet )
                                    { $report += write-output "$Server UP <br>"  
                                    } else
                        { $report += Write-output "$Server <b><font color=red> Down <br>"  
                        }                  
    }
          
    $report  
Send-MailMessage @MessageParams -Body $report -bodyashtml -Priority high


new to PS and need to filter security log for failed logins and output date/time and username

$
0
0

Hi,

I am new to PS. I want to use PS to search the security event log for failed logins and have it output the account name that failed the login, the date/time it occurred, and the reason. Those are the only things I wanted shown.

If I run the following command

GET-EVENTLOG -Logname Security -InstanceId 4625 | export-csv C:\failed.csv

then I get output that had date/time and 4625 events but the Username field is empty for some reason. I would like to know the username that failed the login.

Similary I want to run a command to capture the date/time and username of successful login attempts and have the output only be the date/time and username of the succesful login.

Please help.

Output array to email body

$
0
0

I have the following script and all is working (thanks to advice from this site and Craig Duff). I am now attempting to add a final piece that emails the results. The issue I am having is that I can't get the format of the email body correct.

 

I have tried out-string and format-table with no luck.

The goal is to write to the body of the email the list of users ($user.name) and the the machines ($comp) that were added to the user's LogonRestrictions attribute. In a nice readable table / format.

Any ideas????

####### Begin Script #########

Write-Host "Please select input file"
$initialDir = "\\NP1SECR016v\SECRpt\LogonRestrictionConfig"
Get-FileName $initialDir

# Import the input file.
$items = Import-Csv $gfn_file

$ReportList = @()

$users = $items | Group-Object -Property UserID
$TotalUsers = $users.count
Write-Host $users.count " users to process:"`n`n
ForEach($user in $users)
{
Write-Host `n`n"Processing " $user.Name
$userIDSam = $user.name
$LR = ($user.Group | Select-Object -ExpandProperty LogonRestrictions) -join "," # LR = LogonRestrctions computer list

$LR_report = $LR -split ","

Set-ADUser -Identity $user.Name -LogonWorkstations $LR

$groupArray = $user.Group | Select-Object -ExpandProperty GroupName -Unique
#Add-ADPrincipalGroupMembership -Identity $userGroup.Name -MemberOf $groupArray
Write-host "User added to $groupArray"

foreach ($comp in $LR_report)
{
Write-Host `t$comp
$ExportList = New-Object -TypeName PSObject
Add-Member -InputObject $ExportList -MemberType NoteProperty -Name UserID -Value $userIDSam
Add-Member -InputObject $ExportList -MemberType NOteProperty -Name LR -Value $comp
$ReportList += $ExportList
}
}

write-host `n`n$TotalUsers " users processed"

#$MyData = $ReportList | Group-Object -Property UserID
#$Mydata1 = $ReportList | Format-Table 'Logon Restrictions' -GroupBy UserID
#
#$MyData
#$Mydata = $ReportList | Out-String
#
#
#

write-host "ReportList:"
$ReportList

$mydata = $reportlist | Out-String

#=================CreateEmail
$header = @"

Table {border-width: 1px;border-style: solid; border-color: black;boder-collapse: collapse;}
th {border-width: 1px;padding: 3px;border-style: solid; border-color: black; background-color: #6495ed;}
TD {border-width: 1px;padding: 3px;border-style: solid;border-color: black;}

"@

# Format the email body
$EmailBody += ""
$EmailBody += ""
$EmailBody += "IT Security Operations"
$EmailBody += ""
$EmailBody += ""
$EmailBody += ""
$EmailBody += ""
$EmailBody += ""
$EmailBody += "The following logon restrictions have been set."
$EmailBody += ""
$EmailBody += ""
$EmailBody += "$LR_Report "
$EmailBody += ""
$EmailBody += ""
$EmailBody += "$ReportList "
$EmailBody += ""
$EmailBody += ""

$EmailBody += ""
$EmailBody += " "
$EmailBody += " Users processed"
$EmailBody += " $TotalUsers"
$EmailBody += " "
$EmailBody += " "
$EmailBody += " $MyData"
$EmailBody += " "
$EmailBody += ""
$EmailBody += ""
$EmailBody += ""
$EmailBody += ""
$EmailBody += "Log: $LogPath"
$EmailBody += ""
$EmailBody += ""
$EmailBody += ""
$EmailBody += ""
$EmailBody += ""
$EmailBody += "Script run time: $timeSpan"
#=================End CreateEmail

Send-MailMessage -BodyAsHtml -To "user@companyA.com" -Subject "Logon Restrictions" -SmtpServer xxx.companyA.com -From "support@companyA.com" -Body $Emailbody

####### End Script #########

Error received when running a script

$
0
0

Hello everyone

I would like to explain my situation. I'm using a virtual machine with an admin account but since the account I have don't have enough privileges I used my higher privileges account. I have a server where I use the account with higher privileges but I can't use because it doesn't have power shell installed nor I can install it due to business policies.

So i'm using the first virtual and logging in with the account with higher privileges to powershell and I need to do use a script where it will check a folder and all subfolders, and it needs to display the ACLs.

So far I've found this one (i'm not an expert, i'm learning powershell):

dir \\server\share-Recurse | where { $_.PsIsContainer } | % { $path1 = $_.fullname; Get-Acl $_.Fullname | % { $_.access | where { !$_.IsInherited } | Add-Member -MemberType NoteProperty -name "Path" -Value $path1 -passthru }}

and I get this error:

 

Access to the path 'C:\Users\aaesquivel.BMSL.001\output.csv' is denied.

At line:1 char:234

+ dir "\\bcebffps\BREOF"  -Recurse | where { $_.PsIsContainer } | % { $path1 =

$_.fullname; Get-Acl $_.Fullname | % { $_.access | where { !$_.IsInherited } |

Add-Member -MemberType NoteProperty -name "Path" -Value $path1 -passthru }} > <

<<<  output.csv

    + CategoryInfo          : OpenError: (:) [], UnauthorizedAccessException

    + FullyQualifiedErrorId : FileOpenFailure

 

Thanks in advance!

Hand-Crafted Firewall Rules with PowerShell

$
0
0

I’ve shown you how to configure Windows’ software firewall with PowerShell by discovering its many built-in firewall rules (get-netfirewallrule) and how to enable or disable them (enable-netfirewallrule and disable-netfirewallrule). In reality, though, built-in software firewalls are most useful when you can super-fine-tune them. So, the real power of the Windows Firewall that we’ve had since Windows Server 2008 lies in creating those fine-tuned rules. In fact, I’ve found Windows Firewall rules to be essentially “IPSec made easy.” You won't be surprised, then, to learn that PowerShell’s got a nifty tool to do that: New-NetFirewallRule. This month, you’ll start creating rules (and you'll see how not to disable your computer in the process).

Read More

Trying to create a Powershell script to copy a user profile folder and all of the folders inside to another location

$
0
0

Hi all,

I'm trying to create a Powershell script to copy a user profile folder and all of the folders inside to another location.

I have made this script and for some odd reason it only copies the folders and not the content inside?  Also for example the AppData folder is hidden and it's not copied over?

Any help would be much appreciated as I have been trying to figure this out for hours now.

$destination = "C:\Migration"

$location = "C:\Users\test"

function processCopy

{

 

 $files = Get-ChildItem -Path:$location

 foreach($file in $files)

 {

  $path = $file.FullName

  if($file.Name -ne "copy.ps1"){

  Copy-Item -Path:$path -Destination:$destination -Force -Recurse -Confirm:$false

  Write-Host "Item" $file.Name " has been sucessfully copied to" $destination

  }

  if($file.Attributes -eq "Directory")

  {

   copyFile $file $destination

  }

 }

}

 

function copyFile($directory, $target)

{

 $target +=  $directory.Name

 $files = Get-ChildItem -Force -Recurse -Path:$directory.FullName

 foreach($file in $files)

 {

  $path = $file.FullName

  if($file.Name -ne "copy.ps1"){

  Copy-Item -Path:$path -Destination:$target -Force -Recurse -Confirm:$false

  Write-Host "Item" $file.Name " has been sucessfully copied to" $target

  }

 

  if($file.Attributes -eq "Directory")

  {

   copyFile $file $target

  }

 }

}

#main

processCopy

Add-Content sometimes gives "Stream was not readable" error

$
0
0

I have a script that outputs data to a file using a basic Add-Content command. There's nothing special or unusual about how I'm using it and it works 99% of the time without any problems. But rarely, it will throw the error: "Add-Content : Stream was not readable."  If I run the script again immediately, it will work with no problem. 

The command is executed within a loop, such that the first time it runs, it creates the file (the file is created freshly each day.) On subsequent iterations of the loop, the file may be written to again.

My only guess as to what's going on is that the script is working so fast that occasionally the file system isn't quite ready to accept new input, but that's a total guess. 

The full error is below, and even though it references an invalid argument, I don't believe that's what's actually going on (again, because it will run just fine immediately afterward in a different session.) 

PS C:\WINDOWS> F:\Applications-Non JHA\Development\EOB\temp.ps1

Add-Content : Stream was not readable.

At F:\Applications-Non JHA\Development\EOB\temp.ps1:37 char:25

+                         Add-Content -path ($OutputPath + $AcctNo + ".txt") -valu ...

+                         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : InvalidArgument: (F:\Applications...put\3087832.txt:String) [Add-Content], ArgumentException

    + FullyQualifiedErrorId : GetContentWriterArgumentError,Microsoft.PowerShell.Commands.AddContentCommand

 

Thanks.

select-string searching for "[]"

$
0
0

Hello,

I want to use select-string to look for "![]" in a set of text files, but the error returned is: The string "[]" is not a valid regular expression: parsing "[]" - Unterminated [] set.

Get-ChildItem "somepath" -recurse | select-string -pattern "![]"

I believe it's interpreting [] in a different way.  I've tried placing the ` character in many different places in the command but it's not working.

Thanks for any help you can provide


remoting outside domain

$
0
0

Please forgive me if I ask anything too obvious as I am brand new to Powershell.  I'm trying to establish a remote connection to machines in two separate domains (both outside my current domain).  Using RDP client (mstsc.exe) I can remote no problem - I can also use the Connect-Mstsc function that Jaap Brasser wrote to do the same thing in powershell.  

But after a day of banging my head, for the life of me I can't get PS to connect using PSSession.  For that matter I can't even get the server names to resolve using Test-Connection.  I can ping them both and get a reply with no problem, but can't do anything in PS to establish any connectivity.  I try using host name, FQHN, IP, all to no avail.

FYI in case it might matter for troubleshooting, I'm a domain admin on one of the other servers, but not the other.

If anyone can point me to the error of my ways and/or point me down the path of enlightenment, I'd much appreciate it.

 

thx!

Files not getting deleted using Powershell

$
0
0

I have written the following script using a post on this forum. The script deletes the files which are older than 15 days:

cls$servers = Get-Content server.txt$limit =(Get-Date).AddDays(-15)$path ="E:\CheckDBOutput"

ForEach ($line in$servers){
Invoke-Command -cn line -ScriptBlock { Get-ChildItem -Path $path -Recurse -Force | Where-Object {!$_.PSIsContainer -and$_.CreationTime -lt $limit }| Remove-Item -Force}}

The script is executing fine without errors, but no files are getting deleted.

Kindly tell me what modification should I do for making this script working. Thanks in advance.

in visual studio 2013, how can i get the list of all .net framework classes?

$
0
0

Hi friends

as we know in powershell we can work with .net classes.

but a problem:

in powershell 4.0 we use this command:

New-Object -typename System.Management.Automation.PSCredential

but when i tried to find this in visual studio 2013 & i expanded all items under system.management node one-by-one but i couldn't find it.

backup pst files

$
0
0

I made script for backup pst file on local disk-second partition in folder backuppst. I copied this script on  three machine and I tryed that start but every time I receive error. My script is

<code>If ((get-process | Where-Object{$_.Name -eq "OUTLOOK"}).Count -gt 0) 

{
Stop-Process -name "OUTLOOK" -force
}
$today= Get-Date -format "MM-dd-yyyy HH.mm"
$CurrentDate = Get-Date
$days="-1"
$filterlastwritetime=$CurrentDate.AddDays($days)

$drv=Get-WmiObject -class win32_Logicaldisk | Where { $_.DriveType -eq 3 -and $_.DeviceID -ne 'C:'}
$location= $drv.DeviceID +"\backupmail"
$drvpath=$drv.DeviceID+'\'
$pst=get-childitem "c:\", $drvpath -recurse -ErrorAction SilentlyContinue | where{$_.Path -notlike "*backupmail*" -and $_.extension -like "*.pst"}
if (!(Test-Path -path $location))
{
md $location
Copy-Item $pst.fullname $location -Force -recurse
cd $location
dir | where-object{$_.LastWriteTime -gt $filterlastwritetime} | rename-item -newname {$_.name+ ($today)+".pst"}
}
else
{
Copy-Item $pst.fullname $location -Force -Recurse
cd $location
dir | where-object{$_.LastWriteTime -gt $filterlastwritetime} | rename-item -newname {$_.name+ ($today)+".pst"}
}

$Daysback = "-45"
$DatetoDelete = $CurrentDate.AddDays($Daysback)

Get-ChildItem $location | Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item</code>

Where is error? Thanks

Create Local Group on remote servers

$
0
0

Guys,

I have put together below script (thanks to everyone for posting great scripts). I have copied some part of the script from the forum examples.

This script will take Input, create Domain group and add that domain group to the number of member servers listed in the text file.

So far so good, my this script works fine. 

Question - I need to add functionality in the script to create new local group on member servers using same variable and Add the Domain group (created using same variable) in the newly created local group on member servers.

 

I also want to have an output file for the failed hosts. 

Appreciate your help.

==============================================
# input
$Name = Read-Host "Write Policy Name"


#Create Domain User Group
NEW-ADGroup -Name ${Name}_UserGroup –groupscope Global -path "ou=Test,DC=Lab,DC=Local" -Description "${Name} Domain users Group"

#Read Servers from the Text File
$Servers = Get-Content c:\temp\${Name}_Servers.txt

#Initialize the Domain Group Object 
$DomainGroup = [ADSI]"WinNT://Lab.local/${Name}_usergroup,group"


#Add Domain group to the local Remote Desktop Group on member servers
ForEach ($Server in $Servers) #Loop through each server 


    
    #Get Local Group object 
    $LocalGroup = [ADSI]"WinNT://$Server/Remote Desktop Users,group" 
 
    #Assign DomainGroup to LocalGroup 
    $LocalGroup.Add($DomainGroup.Path)
   
}

==============================

Viewing all 6937 articles
Browse latest View live