Quantcast
Channel: Windows PowerShell Forum
Viewing all 2562 articles
Browse latest View live

Compare-object between 2 txt files that have security updates

$
0
0

Hello,

I have 2 text files that have the following report of the installed patches on 2 different systems.each file for each system:

description                                              hotfixid                                                 InstalledOn                                           
-----------                                              --------                                                 -----------                                           
Update                                                   KB982861                                                   12/3/2012 12:00:00 AM                                  
Update                                                   KB958830                                                 12/4/2012 12:00:00 AM                                  
Update                                                   KB971033                                                 12/4/2012 12:00:00 AM                                  
Update                                                   KB2506143                                                1/14/2013 12:00:00 AM   

I would like to compare between the systems of what is missing between them and compare.

How can I accomplish that with a PowerShell script?

Thank you,

Morris


Dynamically accessing Array items - Is it possible?

$
0
0

I have a script in which I am trying to get information about the header file on the imported CSV, and then once I get the returned info from the header, I will need to then use the returned value to specify the header that I want to return the value for.  [please see the following code].  Let me know if this is possible, or a better way to do this.  Thanks.

[array]$HeaderItems = Import-Csv "C:\NewUserInfo.csv" | get-member -type properties | foreach-object{$_.name}

ForEach ($item in $HeaderItems)
{
    If ($item -ilike "*MemberOf_Groups*")
    {
        [array]$MemberItems += $item
    }
}

$HeaderItems.{$MemberItems[0]}

Powershell Challenge: Export, Alert, and Email

$
0
0

I have been tasked with creating a script that will do the following:

1. Detect on a daily basis all accounts set to expire in the next 30 days.

2. Email the the manager or (if none is listed) the service desk.

3.Track which accounts have been alerted and stop them from recurring the following day.

4.Email them again at 15 days if no action has been taken.

Here is the script that I have come up with so far. If you could give me some help in filling in the holes, then i owe you a cold one!

Search-ADAccount -AccountExpiring -TimeSpan "90" -UsersOnly | Export-CSV C:\export\usersonly.csv | send-mailmessage -from "domains@xxx.com" -to "xxx@xxx.com" -subject "Expiry 90" -body "Here is a list of Users whose account is set to expire in 90 Days." -Attachment "C:\Scripts\usersonly.csv"

hyper-v get-vm cmdlet question

$
0
0

hi Guys

sorry to ask such a simple question but i have to ask because couldn't find the answer after some googling

at my server which is hyper-v server,  when i run this command at powershell :  Get-VM  , i see to  problem :

1) the output has 5 columns ( but i don't want Host and state column be shown )

2 ) Virtual MAchines are listed under VMElementName Column but are not arranged According to  Alphabetic ( or numeric )  order.

my question is , via which command i can reach this two :

1) Host column and state column not be shown

2) Vms listed underVMElementName , be arranged in Alphabetic ( or numeric ) order

?

thank you very much

 




compare-object on multidimensional array?

$
0
0

I have an array with two columns, username and enabled.  I store the array in a variable called $CURRENT.  I make some modifications and then store the new array in a variable called $UPDATED.  The username column is exactly the same in both, but the enabled field may or may not have changes, with values of either TRUE or FALSE. 

What I want to do is take the difference between $CURRENT and $UPDATED to generate a list of only the changes.  Can this be done with compare-object or what other method I can I use? 


If I run compare-object $CURRENT $UPDATED it returns nothing, but there are differences in the two arrays.

Monitoring files - Get-Childitem, GetFiles, WMI, FileSystemWatcher or ?

$
0
0
I am writing a script to send an email notification when certain files change. There is a .CSV that has the File path and filespec (it is in a specific directory, but the filename can vary due to timestamp added to the filename so wildcards are
used) and email address.

I am estimating there are 50 directories containing around 10k files that will be the source I am checking. It is a shared (network) drive.  There are probably about 500 files in the CSV that will need notifications sent.

The notification doesn't have to be instant, it can be done every 15 minutes or so.

My question is, what is the best way to do this?

I originally wrote this using Get-ChildItem.  It would wait 15 minutes, do a GCI where LastWriteTime < 15 min.  This was very slow. Just getting the list of all files changed in the last 15 min took too long.

I then used events with the FileSystemWatcher. This was fast.  The issue I had is duplicate events (well documented) and if the machine running the script goes down (for upgrade, whatever), those events will never be triggered and the emails won't be sent.

I read WMI would work, but heard that is slow too.  

Maybe GetFiles is a little faster than GCI.  I am wondering if I had the wrong approach looking for all files that changed in last 15 min in the source as the starting point and then looking if a file I was looking for was in there. I could start will my list of files to watch, and do a GetFiles every 15 minutes on each file in the list and then check the LastWriteTime. Not sure if that would be faster.

get-aduser filter for displayname endswith null

$
0
0

first off I am a TOTAL Noob with powershell...

just starting to use it and i wanted to search active directory for display names that end in a blank space. I wanted to pipe the output to a text file. i have been hunting around and find things close to this but nothing that quite fits the bill.

Thanks to anyone who has a look at this!

Cheers!

Help understanding PS command?

$
0
0

Ok so I'm new to PS but I'm understanding it step by step and have a question. I have a limited learning resource and am trying to pick this up for my job. I've been doing very good and have noticed this is very similar to a few other scripting languages I've worked with but I'm finding stuff everyday I'm not familiar with. If this is a trivial or simple question then sorry I wasted forum board space for it =P

So I've actually just been going through memorizing commands, practicing them and getting creative.

I was actually just messing around a few different way to run variables and the Get-date command and saw this on TechNet's info page.

(Get-Date).AddMinutes(137)

So I saw that and was just curious if I could run this in a script.

$a = Get-Date "4/26/1990"

#Then run

$a.AddDays(6)

#And sure enough the output was the same as

(Get-date).Addminutes(137)

Although its a different property its still the same idea. My question is what is the purpose of the () and especially the. What roles do they play and could you show me a few examples of how they would be used practically?

From what I understand when you encapsulate a command in (   ) it creates a hash table? If so, is the.  just acting as a way of calling upon a variable after that?

Sorry if this is confusing, I'm trying to explain my question as best as possible, but its also very confusing for me as well!

Any assistance would be GREATLY! appreciated!


inheritable permissions are propagating but showing up as not inherited

$
0
0

I have a folder "Division Restricted Folders" that has 11 ACEs applied, 6 of the ACEs are inherited (see acl = "Division Restricted Folders"). Of the remaining 5 directly applied / not inherited ACEs, only of them "IdentityReference: parentDomain\Provisioning - RF" is set to apply to "This folder, subfolders and files". The other 4 not inherited ACEs are set to "This Folder Only". My issues is when I create a subfolder "test" within "Division Restricted Folders", the single additional ACE "IdentityReference: parentDomain\Provisioning - RF"  that was set to apply to "This folder, subfolders and files" is applied to the folder "test" as not inherited (see acl = "test"). This seems weird because obviously the ACE was inherited, but then seems it un-inherited itself? I've very confused. Something else to note, not sure if it will help, but if I make a subfolder within "test" the same thing happens where all ACEs propagate down but the "IdentityReference: parentDomain\Provisioning - RF" ace shows up again as not inherited. 

acl = "Division Restricted Folders"

PS O:\joey\scripts\powershell> $resFol = get-acl -Path "\\evs-04.childDomain.parentDomain.com\ELC\Division Restricted Folders"
PS O:\joey\scripts\powershell> $resFol.Access


FileSystemRights  : ReadAndExecute, Synchronize
AccessControlType : Allow
IdentityReference : parentDomain\All Divisions - Admin File Access
IsInherited       : False
InheritanceFlags  : None
PropagationFlags  : None

FileSystemRights  : ReadAndExecute, Synchronize
AccessControlType : Allow
IdentityReference : parentDomain\1280-Admin File Access
IsInherited       : False
InheritanceFlags  : None
PropagationFlags  : None

FileSystemRights  : ReadAndExecute, Synchronize
AccessControlType : Allow
IdentityReference : parentDomain\1280-General File Access
IsInherited       : False
InheritanceFlags  : None
PropagationFlags  : None

FileSystemRights  : FullControl
AccessControlType : Allow
IdentityReference : parentDomain\Provisioning - RF
IsInherited       : False
InheritanceFlags  : ContainerInherit, ObjectInherit
PropagationFlags  : None

FileSystemRights  : ReadAndExecute, Synchronize
AccessControlType : Allow
IdentityReference : parentDomain\1280-General File Access (Read Only)
IsInherited       : False
InheritanceFlags  : None
PropagationFlags  : None

FileSystemRights  : FullControl
AccessControlType : Allow
IdentityReference : parentDomain\Domain Admins
IsInherited       : True
InheritanceFlags  : ContainerInherit, ObjectInherit
PropagationFlags  : None

FileSystemRights  : ReadAndExecute, Synchronize
AccessControlType : Allow
IdentityReference : parentDomain\All Divisions - Admin File Access (List Only)
IsInherited       : True
InheritanceFlags  : ContainerInherit
PropagationFlags  : None

FileSystemRights  : ReadAndExecute, Synchronize
AccessControlType : Allow
IdentityReference : parentDomain\All Divisions - Admin File Access (Read Only)
IsInherited       : True
InheritanceFlags  : ContainerInherit, ObjectInherit
PropagationFlags  : None

FileSystemRights  : FullControl
AccessControlType : Allow
IdentityReference : parentDomain\All Divisions - Admin File Access (Full Control)
IsInherited       : True
InheritanceFlags  : ContainerInherit, ObjectInherit
PropagationFlags  : None

FileSystemRights  : ReadAndExecute, Synchronize
AccessControlType : Allow
IdentityReference : parentDomain\1280-Admin File Access (Read Only)
IsInherited       : True
InheritanceFlags  : ContainerInherit, ObjectInherit
PropagationFlags  : None

FileSystemRights  : FullControl
AccessControlType : Allow
IdentityReference : childDomain\Domain Admins
IsInherited       : True
InheritanceFlags  : ContainerInherit, ObjectInherit
PropagationFlags  : None

acl = "test"

PS O:\joey\scripts\powershell> $testFol = get-acl -Path "\\evs-04.childDomain.parentDomain.com\ELC\Division Restricted Folders\test"
PS O:\joey\scripts\powershell> $testFol.Access


FileSystemRights  : FullControl
AccessControlType : Allow
IdentityReference : parentDomain\Provisioning - RF
IsInherited       : False
InheritanceFlags  : ContainerInherit, ObjectInherit
PropagationFlags  : None

FileSystemRights  : FullControl
AccessControlType : Allow
IdentityReference : parentDomain\Domain Admins
IsInherited       : True
InheritanceFlags  : ContainerInherit, ObjectInherit
PropagationFlags  : None

FileSystemRights  : ReadAndExecute, Synchronize
AccessControlType : Allow
IdentityReference : parentDomain\All Divisions - Admin File Access (List Only)
IsInherited       : True
InheritanceFlags  : ContainerInherit
PropagationFlags  : None

FileSystemRights  : ReadAndExecute, Synchronize
AccessControlType : Allow
IdentityReference : parentDomain\All Divisions - Admin File Access (Read Only)
IsInherited       : True
InheritanceFlags  : ContainerInherit, ObjectInherit
PropagationFlags  : None

FileSystemRights  : FullControl
AccessControlType : Allow
IdentityReference : parentDomain\All Divisions - Admin File Access (Full Control)
IsInherited       : True
InheritanceFlags  : ContainerInherit, ObjectInherit
PropagationFlags  : None

FileSystemRights  : ReadAndExecute, Synchronize
AccessControlType : Allow
IdentityReference : parentDomain\1280-Admin File Access (Read Only)
IsInherited       : True
InheritanceFlags  : ContainerInherit, ObjectInherit
PropagationFlags  : None

FileSystemRights  : FullControl
AccessControlType : Allow
IdentityReference : childDomain\Domain Admins
IsInherited       : True
InheritanceFlags  : ContainerInherit, ObjectInherit
PropagationFlags  : None

Check if service is "Running" , if not restart it and log output to screen

$
0
0

All,

I have the following code I am having trouble with.  
I would like it to check to see if a service call "AVSMPROXYSVC" is running and if not start the process.  I would also like to write if the service is running or service is not running for each server in a list.

I need some help to get this straight.

Thank You,

Rob


$servers = Get-Content -Path C:\Load_Stuff\MonitoringScripts\Env2_TS_Servers.txt
ForEach ($server in $servers) {Get-service -ComputerName $server -Name avsmproxysvc }
if ($check -eq $null) {
Write-Host "Process is not running on $server"
Start-Service $server -Name avsmproxysvc
}
else {
Write-Host "Process is running"
}


CURRENT OUTPUT

PS C:\Load_Stuff\MonitoringScripts\PowerShell> .\CheckAVSMProxyEXEup2.ps1

Status   Name               DisplayName
------   ----               -----------
Running  avsm       AVSM  Proxy Service
Stopped  avsm       AVSM  Proxy Service
Running  avsm       AVSM  Proxy Service
Running  avsm       AVSM  Proxy Service
Stopped  avsm       AVSM  Proxy Service
Running  avsm       AVSM  Proxy Service
Running  avsm       AVSM  Proxy Service
Stopped  avsm       AVSM  Proxy Service
Running  avsm       AVSM  Proxy Service
Running  avsm       AVSM  Proxy Service
Running  avsm       AVSM  Proxy Service
Running  avsm       AVSM  Proxy Service
Running  avsm       AVSM  Proxy Service
Process is not running on ts18
Start-Service : A positional parameter cannot be found that accepts argument 'ts18'.
At C:\Load_Stuff\MonitoringScripts\PowerShell\CheckAVSMProxyEXEup2.ps1:5 char:14
+ Start-Service <<<<  $server -Name avsmproxysvc
    + CategoryInfo          : InvalidArgument: (:) [Start-Service], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.StartServiceCommand



OUTPUT desired

Process is not running on ts17 - restarted
Process is not running on ts18 - restarted
Process is not running on ts19 - restarted
Process is running on ts20
Process is running on ts21
Process is running on ts22

setting upn AND suffix with powershell

$
0
0

Hello Technet,

I'm trying to set UPN for multiple users, which I can acheive. But, I would also like the suffix to be set. So far I havent been able to figure out the last part.

The current command I'm using in my test lab:

Get-ADUser -filter * -SearchBase "OU=Users,OU=Users and Groups,OU=05-North-East-F1,DC=f1,DC=lcl"  | select samaccountname | ForEach { Set-aduser -Identity $_.samaccountname -UserPrincipalName $_.samaccountname}

What do I need to add so the suffix will aply also. I.e samaccountname@05.ne.f1.lcl.

For the moment the suffix value is not set to any of the users.

Best Regards

Jesper Vindum, Denmark

convert internal write-progress to Windows.forms.progressbar

$
0
0

If I'm running a cmdlet that takes awhile, often times it will put up the write-progress status bar.  Is there any way to redirect or capture and reshape that progress information to the windows.forms.progressbar GUI element?

Obviously, if my own code has some kind of long loop, I can put up my own progressbar GUI element and update it on each iteration, but how can I do that if I'm just running a single command?  In this particular instance, I would like to make a single export-fimconfig call and have the progress appear in a GUI progress bar (since the PoSh console is not visible at all).

Thanks.

Convert HTML site info to something more readable then pattern search it

$
0
0

Hi,

We have sharepoint site where people post issues, and each team has to manually go in and refresh like every 5 mins to see if there are any issues. What i want to do is grab this sites text, search for certain text, but the problem is when i do this, info comes up in html and its pretty hard to pattern match. My code:

$web = new-object System.Net.WebClient
$web.UseDefaultCredentials = $true
$webpage = $web.DownloadString($url)

I am hopping someone can tell me how to convert this html jibberish to something more readable from which i will then be able to search for our team and new issues?

Thanks for help


Using $variable as Group List in Add-ADPrincipalGroupMembership doesn't work as expected

$
0
0

I am writing a script to create users and assign them to groups among other things.  I would like to add users to several groups and the way I would like to do this is by assigning all the groups to a $GroupList and then passing that to the command like this:

$UserName = "DDuck"

$GroupList = """Finance"", ""IT"", ""Engineering"""

Add-AdPrincipalGroupMembership -Identity $UserName -MemberOf $GroupList

However, this doesn't have the desidered effect.  If I replace the $GroupList with the exact same text that is in the variable, the command works fine. Can anyone shed some light on what I'm doing wrong? 

Error using Invoke-SqlCmd

$
0
0

Receiving error using this script: The TSQL script runs fine but errors in powershell.

Exception             : System.NullReferenceException: Object reference not set to an instance of an object.

                           at BatchParser.ThunkVariableResolver.ResolveVariable(ThunkVariableResolver* , UInt16* varName, UInt16** varValue)

                           at BatchParser.Variables.ResolveVariable(Variables* , basic_string<unsigned short\,std::char_traits<unsigned short>\,std::allocator<unsigned short> >* name, basic_string<unsigned short\,std::char_traits<unsign

                        ed short>\,std::allocator<unsigned short> >* val)

                           at BatchParser.Batch.listall(Batch* , basic_string<unsigned short\,std::char_traits<unsigned short>\,std::allocator<unsigned short> >* str, IVariables* variables, Int32 mark)

                           at BatchParser.Batch.popall(Batch* , basic_string<unsigned short\,std::char_traits<unsigned short>\,std::allocator<unsigned short> >* str, IVariables* variables, Int32 mark)

                           at BatchParser.ExecutionContext.ProcessBatch(ExecutionContext* , Boolean hasNum)

                           at BatchParser.BatchParserYacc.reduce(BatchParserYacc* , UInt32 ulProd, UInt32 ulSize)

                           at SSYacc.doReduce(SSYacc* )

                           at SSYacc.parse(SSYacc* )

                           at BatchParser.BatchParserInternal.Parse(BatchParserInternal* , ParserState* , Boolean flushBatchBuffer)

                           at ManagedBatchParser.Parser.Parse()

                           at Microsoft.SqlServer.Management.PowerShell.ExecutionProcessor.ExecuteTSql(String sqlCommand)

                           at Microsoft.SqlServer.Management.PowerShell.GetScriptCommand.ProcessRecord()

TargetObject          :

CategoryInfo          : InvalidResult: (:PSObject) [Invoke-Sqlcmd], NullReferenceException

FullyQualifiedErrorId : ExecutionFailed,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand

ErrorDetails          :

InvocationInfo        : System.Management.Automation.InvocationInfo

PipelineIterationInfo : {0, 1}

PSMessageDetails      :

cls
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
$server = Get-Content c:\SQL_SERVERS\2008_UPDATE_JOB_STEPS.txt
$updatejob = "C:\SCRIPTS\Maintenance\CURRENT\UPDATE_JOB_STEP.sql"

foreach ($server in $server)
{
try
{
$s = new-object ('Microsoft.SqlServer.Management.Smo.Server') $server
Invoke-Sqlcmd -InputFile $updatejob -ServerInstance $server 
}
catch
{
$Error[0]|format-list -force
Write-Host "Error on $server"
}
}



New-PSDrive does Not appear in Explorer

$
0
0

Hello everybody!

I tried to use the New-PSDrive cmdlet, replacing DOS Subst command. But, the resultant PSDrive is usable within PowerShell ISE only - it does not show up in Windows Explorer. Is there a way to make it appear in Windows Explorer?

There is a problem with the DOS Subst command; that there is no technique for renaming the virtual drive to a more meaningful name, without some undocumented tricks. Secondly, I am trying to learn the unfriendly PowerShell; which offers me a new challenge for every minor task.

Any help with the Cmdlet, please! Take it as a week-end teaser :-)


WMI power supply

$
0
0

Hi all,

Is anyone know, if it's possible to monitor the status of a server's power supply. 

Servers have redundant power supply and I would like to monitor the status of each of them.

Is it possible with WMI ? 

Thank you

is this possible with RegEx, help

$
0
0

Hi, i took html file and converted that in plain text so im seeing alot of words on top of each other things like:

IT - EpicInpatientNoBrown, Ryan P.NewLow (Routine)

IT - EpicSecurityNoFreas, Colin D.NewMedium (Important)

IT - EpicAmbulatoryNo     NewMedium (Important)

So from the above i would like to search the whole document for something like:

IT - EpicInpatient(ignore the NO and the name of submitter),then make sure that status is New, and grab the priority such as Low (Routine)

That will let me know if my team has a new issue and what status...

Any help appreciated

How to query the registry based on a variable?

$
0
0

I have this function i am writing, the purpose is to query any specific registry path desired based on the path being put into a variable.  Here is what I got below:

Function registry {
Write-Host "Enter name of servers: " -NoNewline
$a = Read-Host
$servers = Get-ExchangeServer | ?{$_.name -like "$a*"} | %{$_.name}
foreach ($_ in $servers) {
Write-Host -ForegroundColor Green $_
reg query \\$_\hklm\software\antivirus /s
Write-Host " "
}
}

This part is working as i can enter the first couple characters of the server name and it will match all servers that share the same name syntax.  Question is how could I also do the same for reg query, so that the user enters data the variable is created and the path is populated based on the variable?

Thx all!


JCtech1123, Cheers

Powershell Lastlogon user name

$
0
0

Powershell Lastlogon user name

How do i determine lastlogon username on remote computer

i need only username how do i archive this please assist...


Support@Mytechnet.me

Viewing all 2562 articles
Browse latest View live


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