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

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

 


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.

Can't get a PS script with a funtion to run

$
0
0

Hi,

I think I found a very usefull resource here but I'm unable to run it:

http://jeffwouters.nl/index.php/2013/09/powershell-function-to-get-ntfs-rights-on-a-folder-for-groups-and-users-recursive/

I've tried to run the script directly from a PS window, but whenever I try to execute a simple command, as from EXAMPLES, I get an error:

PS C:\Path> get-ntfspermissions -sharename '\\share\folder' -domain 'domain'

get-ntfspermissions : The term 'get-ntfspermissions' 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, 

The AD module loaded correctly. Any help please?

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

Mapping a Windows shared folder

$
0
0

I need to create a script to map a Windows shared folder. My script looks like:

 

$User = "domain\user"
$PWord = ConvertTo-SecureString -String "password" -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
New-PSDrive -Name M -PSProvider FileSystem -Root \\192.168.1.1\c$ -Credential $Credential -persist

 

 

It works fine if there is no problem while accessing the shared folder.

How can I improve my script so that:

  • If the mapping works fine I get a confirmation
  • If the mapping fails in a given amopunt of time (let's say, 30 seconds) I get an error and the script goes on
  • If the mapping fails I get a return code to understand the reasons because it failed

Can anybody please help?

Regards

marius

 

Uninstall WLAN driver remotely

$
0
0

Hello all,

I am new here, so first a very friendly hello to you all.

I hope you can help me with a little issue. I have to uninstall a wlan driver on a couple of clients, which are scattered in different countries.

So, is it possible to do this using Powershell or WMIC? I didn´t found something useful in the web for that. 

Kind regards.

"Hashtable-to-Object conversion"? geeze, not that

$
0
0

Hi Folks,

I have been away from regular use of PowerShell for a while, and now that I am back, I seem to have forgotten everything!  Reading from a CSV file:

$in=import-csv $InFile 

ForEach ( $address in $in ) { Get-User -Identity $address}

Cannot convert value "@{address=alias}" to type "Microsoft.Exchange.Configuration.Tasks.UserIdParameter". Error: "Cannot convert hashtable to an object of the following type: Microsoft.Exchange.Configuration.Tasks.UserIdParameter. Hashtable-to-Object conversion is not supported in restricted language mode or a Data section."

This is a *trivial* issue and I am sure I am just overlooking something, but what?  How to extract the value of "alias" from the hash?  

Thanks for any help.

--Joe

Foreach logic question

$
0
0

I have a CSV that has the following column headings:

UserIDNameGroupNameLogonRestrictions

 

UserID is the sAMAccountName.

GroupName is the name of an AD group

LogonRestrictions is a machine name.

My current script is as follows:

$inputFile = "\\NP1SECR016v\SECRpt\LogonRestrictionConfig\SSLVPN_Users.csv"

$complist = Import-Csv -Path $inputFile | ForEach-Object {$_.Logonrestrictions} 

foreach($comp in $complist){ 

$comparray += ","+$comp 

Set-ADUser -Identity "H139616" -LogonWorkstations $comparray

#End Script

 

this works great if all the records are for the same UserID. However, the csv that I am given has multiple user accounts. In other words the first 10 records will be for userA with a unique logonrestriction value (10 unique computer names). The next 20 records will be for user B with an entirely different list of computer names. I have like 27 unique user IDs and the total record count is 1800.

 

Is there a clever way to built the $comparray for the first unique user ID then run the set-aduser command and then build the $comparray for the next unique user ID and so on and so on?


Script works locally but not from server

$
0
0

Hello, I am working on a powershell script that looks for a certain folder and if it isn't there it installs a program.

When I run it on a local machine it works fine. When I put it on the server and tie it to a group policy that runs at login or startup it doesn't work.

I was wondering if it was something in the script or whether it was something wrong with group policy. Please have a look at the script and tell me if you see anything that would prevent it from running properly when it isn't run locally.

$Path = "$env:COMPUTERNAME C:\Program Files\SAAZOD" $path2 = "$env:Computername C:\Program Files (x86)\SAAZOD" If((Test-Path -path $Path) -or (Test-Path -Path $path2) -eq $true) {exit} Else {invoke-command { & \actsmartsbs\Applications\AmericanComputer_6201_DPMA_SILENT_526.exe}}

Thanks

check for available hard drive space on a Virtual machine

$
0
0

I'm trying to create a powershell script that will show me how much available HD space is left on each VM

So far i have a text file call machines.txt that have a list off all the VM machines, The below is my command 

$computers = Get-Content -Path "C:\dacto\machines.txt"

Invoke-Command -ComputerName $computers -ScriptBlock {

Get-WmiObject [decimal]::round((Get-WMIObject Win32_LogicalDisk | Where-Object {$_.DeviceID -eq "C:"}).freespace / 1gb)}

But i receive the below errors 
Invalid query 
    + CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], Managemen 
   tException
    + FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.C 
   ommands.GetWmiObjectCommand
 
Invalid query 
    + CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], Managemen 
   tException
    + FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.C 
   ommands.GetWmiObjectCommand
can someone please help im also working on having this script automatically send me an email 
Please and Thank you 

The 3 most compelling updates in Windows Server 10

$
0
0

But don't forget the next iteration of Windows Server -- Windows Server 10, to be exact.

Read More

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

 

 

I always get error when creating users with a script.

$
0
0

Hello,

this is the script that I use :

Import-Module ActiveDirectory 

$Users = Import-Csv -Delimiter ";" -Path "C:\Users\pdj\Documents\ADImportList.csv"  

foreach ($User in $Users)  

{   

    $OU = "OU=users_ou,OU=leraars_ou,DC=edukaronse,DC=be"

    $P = $User.Password 

    $CN= $User.CommonName

    $DN = $User.DisplayName

    $FN = $User.Firstname

    $LN = $User.LastName 

    $UPN = $User.UserPrincipalName

    $SAM = $User.SAM 

    New-ADUser -Name $CN -SamAccountName $SAM -UserPrincipalName $UPN -DisplayName $DN -GivenName $FN -Surname LN -AccountPassword (ConvertTo-SecureString $P -AsPlainText -Force) -Enabled $true -Path $OU -CannotChangePassword $true -PasswordNeverExpires $true

This error is displayed
New-ADUser : Mapobject is niet gevonden
At line:11 char:5
+     New-ADUser -Name $CN -SamAccountName $SAM -UserPrincipalName $UPN -DisplayNa ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (CN=Aelvoet Patr...dukaronse,DC=be:String) [New-ADUser], ADIdentityNotFo
   undException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,M
   icrosoft.ActiveDirectory.Management.Commands.NewADUser
New-ADUser : Mapobject is niet gevonden
At line:11 char:5
+     New-ADUser -Name $CN -SamAccountName $SAM -UserPrincipalName $UPN -DisplayNa ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (CN=Ahmed Abdel,...dukaronse,DC=be:String) [New-ADUser], ADIdentityNotFo
   undException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,M
   icrosoft.ActiveDirectory.Management.Commands.NewADUser
This is the format of my csv file
SAMPasswordDisplayNameLastNameFirstnameCommonName

UserPrincipalName

Who can help me ?

 

 

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

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 #########

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 ~

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

Viewing all 8583 articles
Browse latest View live