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

Where-Object filtering using an array

$
0
0

Greetings! Trying to use Where-Object to filter out the returned data from Get-ChildItem. I essentially want to include everything that matches "Microsoft Lync Server". This works fine for matching "Microsoft Lync Server", but I can't seem to figure out the syntax to exclude those that match anything in the array.

$filter = @("Debugging Tools","Resource Kit Tools","Best Practices Analyzer","Meeting Room Portal")
(Get-ChildItem HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall | ForEach-Object {Get-ItemProperty $_.pspath} | Where-Object {$_.DisplayName -imatch "Microsoft Lync Server"}) | Select-Object DisplayVersion,displayname | Sort-Object DisplayVersion -Descending 

I've tried using something like

(Get-ChildItem HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall | ForEach-Object {Get-ItemProperty $_.pspath} | Where-Object {$_.DisplayName -imatch "Microsoft Lync Server" -and $_.DisplayName -notin $filter}) | Select-Object DisplayVersion,displayname | Sort-Object DisplayVersion -Descending 

As well as -notcontains -notmatch, etc. to no avail. Ideas?



Finding login events to a list of remote comptuers without using AD

$
0
0

Hello,

I've been tasked with finding users who have logged into a list of remote computers.  I'm thinking the easiest way is to use the Security Event Log. To that end I found a great script here:  https://github.com/pdxcat/Get-LogonHistory/blob/master/Get-LogonHistory.ps1 that will scan either the local computer or one remote computer.  I'm going to have to modify this script to read in a list of computers.

But when I ran this I quickly discovered that it lists users from my teamthat login to do various tasks. I would want to be able to exclude some usernames and only zero in on userids of people not from my team. Here are some changes I would like to make to this script...I'm hoping someone here can assist me:

  • Add in the ability to read in a list of computers from a text file.
  • Read in an exclude file to check if a UserName is in the exclude file and skip recording the excluded name in the output.
  • Write out results to a spreadsheet.  This could be daunting as each server/desktop could have many (many) records of login. So using a spreadsheet means I could at least filter out what I need.
  • This script appears to handle only Windows XP and Windows 7.  The machines I'm scanning could be any O/S (Windows XP, Windows 7, Windows 2000, Windows 2003, Windows 2008).  Would I need to modify this script to handle these other O/S's?

Here is the script I'm working from:

<#
.Synopsis
    Extracts recent logon history for the local machine from the Security Event Log.
.Description
    This script scans through the Security Event Log on the local machine for interactive logons (both local and remote), and logouts.
    It then constructs a PowerShell Custom Object containing the fields of interest and writes that object to the pipeline as its output.
    NOTE: This script must be run 'As Administrator' in order to access the Security Event Log.
    To run this function on a remote computer, use it in conjunction with the Invoke-Command cmdlet.
.Inputs
    None. You cannot pipe input to this script.
.Outputs
    System.Management.Automation.PSCustomObject
    Get-LogonHistory returns a custom object containing the following properties:
    [String]UserName
        The username of the account that logged on/off of the machine.
    [String]ComputerName
        The name of the computer that the user logged on to/off of.
    [String]Action
        The action the user took with regards to the computer. Either 'logon' or 'logoff'.
    [String]LogonType
        Either 'console' or 'remote', depending on how the user logged on. This property is null if the user logged off.
    [DateTime]TimeStamp
        A DateTime object representing the date and time that the user logged on/off.
.Notes
.Example
    .\Get-LogonHistory.ps1
    Description
    -----------
    Gets the available logon entries in the Security log on the local computer.
.Example
    Invoke-Command -ComputerName 'remotecomputer' -File '.\Get-LogonHistory.ps1'
    Description
    -----------
    Gets the available logon entries in the Security log on a remote computer named 'remotecomputer'.
#>




function Get-Win7LogonHistory {
    $logons = Get-EventLog Security -AsBaseObject -InstanceId 4624,4647 |
              Where-Object { ($_.InstanceId -eq 4647) `
                        -or (($_.InstanceId -eq 4624) -and ($_.Message -match "Logon Type:\s+2")) `
                        -or (($_.InstanceId -eq 4624) -and ($_.Message -match "Logon Type:\s+10")) }
    $poweroffs = Get-EventLog System -AsBaseObject -InstanceId 41
    $events = $logons + $poweroffs | Sort-Object TimeGenerated
    if ($events) {
        foreach($event in $events) {
            # Parse logon data from the Event.
            if ($event.InstanceId -eq 4624) {
                # A user logged on.
                $action = 'logon'
                $event.Message -match "Logon Type:\s+(\d+)" | Out-Null
                $logonTypeNum = $matches[1]
                # Determine logon type.
                if ($logonTypeNum -eq 2) {
                    $logonType = 'console'
                } elseif ($logonTypeNum -eq 10) {
                    $logonType = 'remote'
                } else {
                    $logonType = 'other'
                }
                # Determine user.
                if ($event.message -match "New Logon:\s*Security ID:\s*.*\s*Account Name:\s*(\w+)") {
                    $user = $matches[1]
                } else {
                    $index = $event.index
                    Write-Warning "Unable to parse Security log Event. Malformed entry? Index: $index"
                }
            } elseif ($event.InstanceId -eq 4647) {
                # A user logged off.
                $action = 'logoff'
                $logonType = $null
                # Determine user.
                if ($event.message -match "Subject:\s*Security ID:\s*.*\s*Account Name:\s*(\w+)") {
                    $user = $matches[1]
                } else {
                    $index = $event.index
                    Write-Warning "Unable to parse Security log Event. Malformed entry? Index: $index"
                }
            } elseif ($event.InstanceId -eq 41) {
                # The computer crashed.
                $action = 'logoff'
                $logonType = $null
                $user = '*'
            }
            # As long as we managed to parse the Event, print output.
            if ($user) {
                $timeStamp = Get-Date $event.TimeGenerated
                $output = New-Object -Type PSCustomObject
                Add-Member -MemberType NoteProperty -Name 'UserName' -Value $user -InputObject $output
                Add-Member -MemberType NoteProperty -Name 'ComputerName' -Value $env:computername -InputObject $output
                Add-Member -MemberType NoteProperty -Name 'Action' -Value $action -InputObject $output
                Add-Member -MemberType NoteProperty -Name 'LogonType' -Value $logonType -InputObject $output
                Add-Member -MemberType NoteProperty -Name 'TimeStamp' -Value $timeStamp -InputObject $output
                Write-Output $output
            }
        }
    } else {
        Write-Host "No recent logon/logoff events."
    }
}


function Get-WinXPLogonHistory {
    $logons = Get-EventLog Security -AsBaseObject -InstanceId 528,551 |
              Where-Object { ($_.InstanceId -eq 551) `
                        -or (($_.InstanceId -eq 528) -and ($_.Message -match "Logon Type:\s+2")) `
                        -or (($_.InstanceId -eq 528) -and ($_.Message -match "Logon Type:\s+10")) }
    #$poweroffs = Get-Eventlog System -AsBaseObject -InstanceId 6008
    #$events = $logons + $poweroffs | Sort-Object TimeGenerated
    if ($events) {
        foreach($event in $events) {
            # Parse logon data from the Event.
            if ($event.InstanceId -eq 528) {
                # A user logged on.
                $action = 'logon'
                $event.Message -match "Logon Type:\s+(\d+)" | Out-Null
                $logonTypeNum = $matches[1]
                # Determine logon type.
                if ($logonTypeNum -eq 2) {
                    $logonType = 'console'
                } elseif ($logonTypeNum -eq 10) {
                    $logonType = 'remote'
                } else {
                    $logonType = 'other'
                }
                # Determine user.
                if ($event.message -match "Successful Logon:\s*User Name:\s*(\w+)") {
                    $user = $matches[1]
                } else {
                    $index = $event.index
                    Write-Warning "Unable to parse Security log Event. Malformed entry? Index: $index"
                }
            } elseif ($event.InstanceId -eq 551) {
                # A user logged off.
                $action = 'logoff'
                $logonType = $null
                # Determine user.
                if ($event.message -match "User initiated logoff:\s*User Name:\s*(\w+)") {
                    $user = $matches[1]
                } else {
                    $index = $event.index
                    Write-Warning "Unable to parse Security log Event. Malformed entry? Index: $index"
                }
            }# elseif ($event.InstanceId -eq 6008) {
                # The computer crashed.
            #    $action = 'logoff'
            #    $logonType = $null
            #    $user = '*'
            #}
            # As long as we managed to parse the Event, print output.
            if ($user) {
                $timeStamp = Get-Date $event.TimeGenerated
                $output = New-Object -Type PSCustomObject
                Add-Member -MemberType NoteProperty -Name 'UserName' -Value $user -InputObject $output
                Add-Member -MemberType NoteProperty -Name 'ComputerName' -Value $env:computername -InputObject $output
                Add-Member -MemberType NoteProperty -Name 'Action' -Value $action -InputObject $output
                Add-Member -MemberType NoteProperty -Name 'LogonType' -Value $logonType -InputObject $output
                Add-Member -MemberType NoteProperty -Name 'TimeStamp' -Value $timeStamp -InputObject $output
                Write-Output $output
            }
        }
    } else {
        Write-Host "No recent logon/logoff events."
    }
}
$OSversion = (Get-WmiObject -Query 'SELECT version FROM Win32_OperatingSystem').version
if ($OSversion -ge 6) {
    Get-Win7LogonHistory
} else {
    Get-WinXPLogonHistory
}

SharePoint Online Recycle Bin and accessing via Powershell

$
0
0

Is it possible to access the SharePoint Online Site Collection Recycle Bin?  If there are, are there any samples to review as a template?

Problem accessing localhost in powershell

$
0
0

I have two system that are identical.  Both run windows 7 pro 64bit.  I have a script that I run on both systems.  It works on one system but not the other.  The script is as follows:

$ie = new-object -com "InternetExplorer.Application"
$ie.navigate("http://localhost:8129/default.aspx")
#$ie.visible = $true
$ie.visible = $false
$b=0
$doc = $ie.document

On one system it opens the page and $doc contains the correct data.  Also the window is not visible.  ON the other system it opens the page and the window is visible.  The $doc has no data.  If on the system that fails.  I navigate to www.google.com.  I does not display the window and $doc contains valid data.

RAC

Cannot find path .... because it does not exist. WHY??

$
0
0

Where am I failing guys??

I have a directory named Learning Powershell [Do Whatever] in E:\, and when I try to change directory  (cd) it pops up a error.

I have just started to learn, so if you explain me this to me in a simple language, it would be most appreciated.

Thank You.

Set-ADAccountPassword failing

$
0
0

Good morning People of the Powershell!

My question isn't as simple as it sounds.  To "pre-disable" users in our environment, we run a script which changes their password, removes their group memberships, gives someone fullaccess to their mailbox, and sets up an out of office message for their email.  The script is crafted by a program I created, and we have it run at a set time with Task Scheduler.  In addition to the above tasks, it runs another set of cmdlets the results of which are then emailed to us and serve to let us know whether the script was successful.  So for example, we change the password and then get the results of passwordlastset.  We remove their group memberships, then get their group memberships.  Set the out of office, get the out of office.

We've just started doing this and for the most part it has worked wonderfully.  But on two occasions, the password failed to be changed.  It makes no sense to me and I'm hoping that someone here will have a suggestion.

Here's an example of the cmdlet:  Set-ADAccountPassword -Identity DBLACKLE -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "Phoenix4" -Force)

On both of these two occasions, in an attempt to determine what went wrong I ran the passwordlastset cmdlet again to verify I got the same results.  I did.  I would then copy/paste the exact cmdlet from the script into Powershell and it would complete successfully.  So I don't believe it's a time-out issue nor a problem with the cmdlet syntax or with the chosen password - if it was, it would fail when I ran it later.  If it matters, this is the first cmdlet in the script - it runs right after with import-ad and whatnot.

It's certainly possible, though unlikely, that the user is logged in at the time this is run, but I don't think that would cause it to fail?

I'm hoping someone here will have experience with this particular cmdlet and will know what if any common issues there might be.  And/or I'm open to suggestions on how to capture the results of this particular cmdlet.  When I set this up I wanted to capture results for each cmdlet but for some reason that didn't work out; that's why I run all the "gets" later and stuff them into a txt file.

Here's the full text of the script in case it's useful:

import-module activedirectory
Add-PSSnapin Quest.ActiveRoles.ADManagement
New-PSDrive -name H -psprovider FileSystem -root \\napvmfsr01\users\dcarnes\virtualgray\

Set-ADAccountPassword -Identity DBLACKLE -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "Phoenix4" -Force)


Add-MailboxPermission -Identity 'CN=Blackl\, Donald L.,ou=Phoenix,ou=QBUsers,dc=na,dc=qb,dc=llp' -User 'NA\JBRACCIA' -AccessRights 'FullAccess'

Set-MailboxAutoReplyConfiguration DBLACKLE -AutoReplyState enabled -ExternalAudience all -InternalMessage "This is an automated reply: ___ no longer practices law at ___.  ___'s messages will be monitored by his former assistant, J B, for 30 days (5/30/14 until 6/30/14).  Messages related to client matters will be forwarded to ___, Phoenix Chair of the Corporate Services group.  If you would like your message or any other matter addressed by another ___ attorney, please contact either that attorney directly or contact ___ at ___. Thank you." -ExternalMessage "You get the idea."

Get-Content \\napvmfsr01\users\dcarnes\virtualgray\oktodeleteDBLACKLE.txt | ForEach-Object {
Remove-AdGroupMember -Identity $_ -Member DBLACKLE -Confirm:$false
}

get-aduser -identity DBLACKLE -properties passwordlastset | select passwordlastset | out-file \\napvmfsr01\users\dcarnes\virtualgray\ResultsDBLACKLE.txt

Get-MailboxPermission -Identity DBLACKLE -User "JBRACCIA" | out-file -Append \\napvmfsr01\users\dcarnes\virtualgray\ResultsDBLACKLE.txt

Get-ADPrincipalGroupMembership DBLACKLE | Select Name | out-file -Append \\napvmfsr01\users\dcarnes\virtualgray\ResultsDBLACKLE.txt

Get-MailboxAutoReplyConfiguration DBLACKLE | select internalmessage | format-table -wrap -autosize | out-file -Append \\napvmfsr01\users\dcarnes\virtualgray\ResultsDBLACKLE.txt

function sendMail{
Write-Host "Sending Email"
#SMTP server name
$smtpServer = "___"
#Creating a Mail object
$msg = new-object Net.Mail.MailMessage
#Creating SMTP server object
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
#Email structure
$msg.From = "___"
$msg.ReplyTo = "___"
$msg.To.Add("___")
$msg.subject = "Pre-Disable Results for DBLACKLE"
$msg.body = Get-Content \\napvmfsr01\users\dcarnes\virtualgray\ResultsDBLACKLE.txt

#Sending email
$smtp.Send($msg)

}
#Calling function
sendMail

$ExecuteContext.InvokeCommand.ExpandString: different behavior in v4 over v2

$
0
0

In PowerShell v2 this would work just fine, but in PS v4 it throws an error "Object reference not set to an instance of an object." Well, color me confused because, yeah, it's a string, what with me wanting to ExpandString and all. ;)

$Replacement = '$(Split-Path $global:ScriptPath -Parent)'
$Replacement = $ExecuteContext.InvokeCommand.ExpandString($Replacement
)

For some context, I am using an XML file as a lookup table, and some of the references in the lookup table include variables such as my $global:ScriptPath as well as env:computername, env:username, etc. And in some cases I would like to define in the lookup further processing, like here where I actually want the parent folder. I need to be able to read the string out of the lookup table and expand it if needed to real data.

So, any hope for getting this to work in v4, or am I gimped for those VERY few users who are moving to Windows 8? Honestly, if it just can't be done I am not going to cry, I doubt if 1% of my customers are even seriously looking at Windows 8. But if it is any easy fix, I would rather support that 1%.

Gordon

"Contains" question

$
0
0

Can anyone see what is wrong with the "-contains" logic below?  I don't know if I have to somehow refer to an attribute of the $lineitem object or something else but any feedback would be great. 

The file being read is below the code.

{$columnCnt = 1
     $childrenPath = $childrenRoot + "\" + $child.Name
     $RawData = get-content $ChildrenPath | select-object -Skip 4
     forEach($lineItem in $rawData)
          {$columnCnt++
           If ($lineItem -contains ">domainFunctionality:")
               {$cells.item($cellCnt,$columnCnt) = $lineItem}
                If ($lineItem -contains ">forestFunctionality:")
                    {$cells.item($cellCnt,$columnCnt) = $lineItem}
               }
 }

----------------------------------------------------------------------------------------------

Using server: OGGP-PP3ADC02.root.domain.com:389
Directory: Windows Server 2008

>domainControllerFunctionality: 3 [Windows Server 2008 Mode]
>domainFunctionality: 2 [Windows Server 2003 Domain Mode]
>forestFunctionality: 2 [Windows Server 2003 Forest Mode]

1 Objects returned


Paul Bergson
MVP - Directory Services
MCITP: Enterprise Administrator
MCTS, MCT, MCSE, MCSA, Security, BS CSci
2012, 2008, Vista, 2003, 2000 (Early Achiever), NT4
Twitter @pbbergs http://blogs.dirteam.com/blogs/paulbergson
Please no e-mails, any questions should be posted in the NewsGroup.
This posting is provided AS IS with no warranties, and confers no rights.


Issue with variable while in a PSSession connected to an end point

$
0
0

Ok so Ive put together a simple script that will allow our helpdesk to look at permissions on a specified folder or share adn display in a nice html page.  I need it to run under different credentials so I set up an endpoint which I can connect to remotely and run the script.  The issue is in the variable that needs to get set.  It prompts for the folder location and once you put it in, it just freezes up.  If I run the script locally its fine and works perfectly.  but running it in the remote session connected to an end point, it just doesnt do anything once you put in the information after it prompts you.  For testing also I set the $folderpath to a specific path  and it does run fine through a remote session so its just an issue passing that input back to the variable while in the remote session.  Any idea?

$a = "<style>"
$a = $a + "BODY{background-color:peachpuff;}"
$a = $a + "TABLE{border-width: 0px;border-style: solid;border-color: black;border-collapse: collapse;}"
$a = $a + "TD{border-width: 3px;padding: 5px;border-style: solid;border-color: black;background-color:PaleGoldenrod}"
$a = $a + "</style>"
$folderpath = Read-Host -Prompt "Enter full folder path here"
$cname ="Permissions for $folderpath : "
Get-Acl $folderpath | select access -ExpandProperty access| select identityReference | ConvertTo-HTML -head $a -body "<H2>$CNAME</H2>"  | Out-File \\server\PermReports\perms.html

Powershell Version

$
0
0

I have seen few PSP's are typed "host" for getting the Powershell Version but there is an issue if we are using "Enter-PSSession". We will not get expected result. See the output but there PS ver. is 2.

[JBL-ADS0034]: PS C:\> host


Name             : ServerRemoteHost
Version          : 1.0.0.0
InstanceId       : 5307c6d7-4545-4530-8235-e3d7ae6c28f8
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : en-US
CurrentUICulture : en-US
PrivateData      :
IsRunspacePushed :
Runspace         :

Alway use $psversiontable for getting the PS ver.

[JBL-ADS0034]: PS C:\> $psversiontable

Name Value
---- -----
CLRVersion 2.0.50727.4927
BuildVersion 6.1.7600.16385
PSVersion 2.0
WSManStackVersion 2.0
PSCompatibleVersions {1.0, 2.0}
SerializationVersion 1.1.0.1
PSRemotingProtocolVersion 2.1


Regards~Biswajit

Disclaimer: This posting is provided & with no warranties or guarantees and confers no rights.

MCP 2003,MCSA 2003, MCSA:M 2003, CCNA, MCTS, Enterprise Admin

MY BLOG

Domain Controllers inventory-Quest Powershell

Generate Report for Bulk Servers-LastBootUpTime,SerialNumber,InstallDate

Generate a Report for installed Hotfix for Bulk Servers


String Comparison based on EXE output

$
0
0

I got the code below

$URL = "http://content3.catalog.video.msn.com/e2/ds/3416835b-d0fc-412a-8de5-d2101ff48341.mp4"
$wget = "C:\Program Files (x86)\GnuWin32\bin\wget.exe"
$URLfilesize = &$wget -S --spider $URL | Out-String

I have used wget to download, I know there are powershell commands to do it but I prefer wget for some reason. I get the output as below

HTTP request sent, awaiting response...
  HTTP/1.0 200 OK
  Content-Length: 511726956
  Content-Type: video/mp4
  Last-Modified: Wed, 14 May 2014 16:14:31 GMT
  Accept-Ranges: bytes
  Server: Microsoft-IIS/8.0
  Access-Control-Allow-Origin: *
  X-AspNet-Version: 4.0.30319
  X-Powered-By: ASP.NET
  Cache-Control: public, max-age=915969
  Expires: Thu, 12 Jun 2014 03:39:48 GMT
  Date: Sun, 01 Jun 2014 13:13:39 GMT
  Connection: keep-alive
Length: 511726956 (488M) [video/mp4]
Remote file exists.

How do I continue from there so that I get the Length: 511726956 (488M) [video/mp4] (Only the bold and highlighted)

Also, is there a way that masked the above output so that it will not be displayed on the console?

I know there are methods to pipe to a file and then grab the content but I prefer the output to go directly to a string and we can manipulate the values from there?




Thanks

What permissions are needed on the client side for RunspaceFactory.CreateRunspace?

$
0
0

Hi.

I am running a remote powershell command from an IIS application to an Exchange server getting the below error. Everything works fine if the IIS application pool identity is in the local administrators group on the IIS server so we can rule out issues with firewall or anything on the Exchange server. It is a problem with lack of privileges on the local server. 

So my question is: What permissions are required on the local server for RunspaceFactory.CreateRunspace? I find good documentation on the permissions required on the server side, but nothing about the client side.

The last Win32 error code after failure is 1008.

An internal error occurred. 
at at System.Management.Automation.Remoting.Client.WSManClientSessionTransportManager.Initialize(Uri connectionUri, WSManConnectionInfo connectionInfo) 
at System.Management.Automation.Remoting.Client.WSManClientSessionTransportManager..ctor(Guid runspacePoolInstanceId, WSManConnectionInfo connectionInfo, PSRemotingCryptoHelper cryptoHelper) 
at System.Management.Automation.Remoting.ClientRemoteSessionDSHandlerImpl..ctor(ClientRemoteSession session, PSRemotingCryptoHelper cryptoHelper, RunspaceConnectionInfo connectionInfo, URIDirectionReported uriRedirectionHandler) 
at System.Management.Automation.Remoting.ClientRemoteSessionImpl..ctor(RemoteRunspacePoolInternal rsPool, URIDirectionReported uriRedirectionHandler) 
at System.Management.Automation.Internal.ClientRunspacePoolDataStructureHandler..ctor(RemoteRunspacePoolInternal clientRunspacePool, TypeTable typeTable) 
at System.Management.Automation.Runspaces.Internal.RemoteRunspacePoolInternal..ctor(Int32 minRunspaces, Int32 maxRunspaces, TypeTable typeTable, PSHost host, PSPrimitiveDictionary applicationArguments, RunspaceConnectionInfo connectionInfo) 
at System.Management.Automation.Runspaces.RunspacePool..ctor(Int32 minRunspaces, Int32 maxRunspaces, TypeTable typeTable, PSHost host, PSPrimitiveDictionary applicationArguments, RunspaceConnectionInfo connectionInfo) 
at System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspacePool(Int32 minRunspaces, Int32 maxRunspaces, RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable, PSPrimitiveDictionary applicationArguments) 
at System.Management.Automation.RemoteRunspace..ctor(TypeTable typeTable, RunspaceConnectionInfo connectionInfo, PSHost host, PSPrimitiveDictionary applicationArguments) 
at System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable, PSPrimitiveDictionary applicationArguments) 
at System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(RunspaceConnectionInfo connectionInfo) 

don't copy duplicate files

$
0
0

Hello,

i must copy files and i want use powershell. I want omit copy if the content of the file is the same (i want have 1 copy this file).

i'm know that must use get-content but i don't know how omit duplicate files


Can you help me?

bernicls

Delete DHCP reservations

$
0
0

Hi all

I have identified a high number of dead DHCP reservations (300+) on my DHCP server from old printers and dead computers that are no longer used. I have a list of IPs (from different scopes) in a text file that need deleting. As a Powershell novice, I have looked online for a script to help me achieve this - I have seen Jeremy Engel's which seems to do the trick. However, I just need a little clarification on one of his examples.

Remove-DHCPReservation -Server dhcp01.contoso.com -Scope 192.168.1.0 -IPAddress 192.168.1.237 -MACAddress 00:00:00:00:00:00 

#This example removes the reservation for 192.168.1.237 from the 192.168.1.0 scope on dhcp01.contoso.com. 

Can I get away with using just the IP as the unique lookup value and not having to supply the MAC and scope?

Jeremy's PowerShell module for DHCP can be found here.

Also, do any of you know where I can find a sample vhd or similar of a DHCP setup to test with for Server 2008 R2?

Thanks!


Excel vba graph xvalue updating but not showing on the graph

$
0
0

I have a line graph in Excel with 4 sets of data for the lines and one set of data for the labels (months in this case (xvalues)). The data and months work fine. When I change to Weeks it also works except the last few labels are missing. If I check the graph data it has selected the correct entries (say A1:A100) but the graph is only showing the first 90 or so.

When you go into the chart data the X axis values are displayed with a tick box next to them.  The data only shows about the first 50 entries, then I see '....' at the end.  What I'm thinking is that the last few entries may not be ticked for some reason?  Is there anyway to check this? 

I am currently using:
   ActiveChart.SeriesCollection(1).XValues = Worksheets("SPC Chart").Range("$A$9:$A$109")
to set the labels (although the range is not hard coded as above, it uses a variable to set the last row)

Anyone got any ideas?  Maybe I need to remove the range completely and then re-add it to ensure all are displayed?  Or something the ensures all entries in the range are 'ticked' to display them?

Thanks
Garry


PowerShell Script to fetch Logon/Logoff user on particular server {Get-WinEvent} {Get-EventLog}

$
0
0

Hello,

I'm looking for a script which can fetch for me a username that he/she loges in on all the servers.

I have tried several scripts, but it doesn't fetch the information i'm looking for.

Get-EventLog Security -ComputerName Computer  -Source Microsoft-Windows-Security-Auditing | Where {$_.InstanceID -like "4624"} | Select $UserProperty | where {$_.Username -Like "username"} | Export-Csv D:\Logon.csv -NoTypeInformation

Or to loop through a file contains the server names and fetch the required details based on the username.

Any help



copy and edit files

$
0
0

Hello,
In directory i have 19 file txt. i must copy the files to other directory and shorten all files name to 10 characters (without extension)
Files with the same name i should be added to the end character "_" and the next digit will starting at 0 .

Can you help me?

bernicls

What are these Commands??

$
0
0

I wanted to know what these commands are? and what are they used for?.

I have just started to learn PowerShell, so if you explain this to me in a simple language, it would be most appreciated.

  forfiles

  runas

  attrib

  icacls

Thank You.

Unpin from Task bar AFTER program is deleted

$
0
0

I have a situation where I am trying to use PowerShell to Unpin a shortcut from the task bar after the program has been deleted. The shortcut has been renamed (from the idiotic name Autodesk used to start with) and thus it is orphaned after uninstall because Windows doesn't manage these things gracefully. The code I am using uses the common approach of digging into the shortcut to extract the Verbs array, and then assigned the Unpin verb to $Verb and then does a $Verb.DoIt(). But of course the the target no longer exists, so there is no Verbs object to dig a Verb out of. 

I have found the various related posts, and there are issues
1: Deleting the reg key and losing all pinned items is a no go. I am removing one piece of software, and I want to remove that shortcut and no others.
2: I know I can do this manually, but my whole goal is automation, and the fact that I CAN do it manually suggests there should be a way to do it with PowerShell.
3: I have tried getting the Verb from the shortcut as well, but it seems like the shortcut really is just a passthrough to the Target, so no target, no Verb from the shortcut.
4: I have also tried just deleting the shortcut file from User\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar, but that leaves an even more orphaned shortcut on the task bar, that not only doesn't have a target, it doesn't even have an icon, just a white "page".

So, how does one get to whatever Verbs are being accessed when doing this manually? Is there some way to apply a generic Verb?

Gordon

Browse log on remote computers

$
0
0

Hello,

this might be a stupid question, but how do i get computername to the output together with value i search for?

cat .\remotecomputers.txt | %{cat \\$_\c$\example.log | select-string -Pattern $regex}

.. im getting values from log files, but i cannot see the computer name it came from

thx

Viewing all 21975 articles
Browse latest View live


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