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

Encrypt script

$
0
0

Hi

I am sick of my colleague stealing the codes from my script and claim that as his own work. Is there a way of encrypting the script so he cant view the content of the script but at the same time he can run the script.


Timer Triggered continue in a foreach loop

$
0
0

Hello all,

before digging into the script, maybe someone sees something I missed...

$range = 1..100 
ForEach ($_ in $range){
    if ($_ % 7 -ne 0 ) { continue; }
    $timer = New-Object System.Timers.Timer
    Register-ObjectEvent -InputObject $timer -EventName Elapsed -Action { continue; }
    $timer.Interval = 1000
    $timer.Autoreset = $false
    $timer.Enabled = $true
    Start-Sleep -s 10
    Write-Host "$($_) is a multiple of 7"
}

What I am trying to do is skip one step in a foreach loop (basically when a WMI Query does not finish, though that's not in the example code). So in general, using continue works fine (if mod 7 != 0 will skip the step of the foreach loop), using continue with the timer wont work. if I replace the continue; in the action with eg Write-Host 'Event Fired';, I can see that the Timer as such does work and does fire the event.

Curious, should it work or have I missed the obvious?

Thanks

Florian

Question: Email Script lowest rights to execute

$
0
0
I have a email script setup to e-mail users when there password is about to expire. I want to run it with the lowest credentials possible. I don't want them to be a domain admin. Any ideas?

Using EWS to cancel a meeting in a room mailbox.

$
0
0

This seems like a common occurance at any company but there really doesn't seem to be a solution for it.  In Exchange people can reserve a conference room by inviting it to a meeting and with the proper setup the room mailbox will accept the meeting if the time slot is free.  The problem comes in when the organizer of the meeting leaves the company.  I'm working on a project using Exchange Web Services to clean out our room mailboxes of meetings which were scheduled by people who are no longer at the company.  The only way I know how is through web services and through an account that has been given the impersonation right (which I am using).

The problem I'm having is that through web services there is a method on an appointment item called CancelMeeting which would do just this except I'm getting the below error:

Exception calling "CancelMeeting" with "0" argument(s): "User must be an organizer for CancelCalendarItem action."

I'm looking for any suggestions as I've been looking out over the Internet for quite a bit now and not really coming up with anything of use.  Below is the code I'm using (cleaned up to remove company information).  Any thoughts or input that could be helpful would be much appreciated.

#Address of object to connect to
$roomAddress = 'room@contoso.com'

#Path to the EWS DLL
$dllpath = "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll"

#Load the EWS DLL
[void][Reflection.Assembly]::LoadFile($dllpath)
	
#Create a service object that supports Exchange 2010 SP1
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1)
	
#Store the passed in credential
#$service.Credentials = $credential

#Web services url
$uri=[system.URI] "https://ExhcangeServer.Contoso.com/EWS/Exchange.asmx"
$service.Url = $uri
#The impersonation details.
$ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId
$ImpersonatedUserId.IdType = 'smtpaddress'
$ImpersonatedUserId.Id = $roomAddress
$service.ImpersonatedUserId = $ImpersonatedUserId
#Build a folder ID object
$folderid = new-object  Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Calendar,$roomAddress)
#Bind to the mailbox and folder.
$CalendarFolder = [Microsoft.Exchange.WebServices.Data.CalendarFolder]::Bind($service,$folderid)
#Get up to 2000 entries from the folder and find any that are appointments from today and the next 5 days.
$startDAte = get-date
$endDate = (get-date).AddDays(+5)
$cvCalendarview = new-object Microsoft.Exchange.WebServices.Data.CalendarView($StartDate,$EndDate,2000)
$frCalendarResult = $CalendarFolder.FindAppointments($cvCalendarview)
#Build a view
$psPropset = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
$psPropset.RequestedBodyType = [Microsoft.Exchange.WebServices.Data.BodyType]::Text

#Cancel the first meeting found (there is one here)
$frCalendarResult.Items[0].CancelMeeting()


Group membership and memberof information

$
0
0

Scenario,

We have around 50 Groups each group is nested into differen group or is member of different group.

We are building different forest and need that information

Need powershell script that will get (information about group membership and export int o excel)

1) Group members information

2) Group memberof information

script to export share folder NTFS security permission

$
0
0

Hi

I got below one script to export share folder permission. But I am not getting where can i define the share folder path in the below script.

===============Script=============

Function Get-NtfsRights($name,$path,$comp) {$path=[regex]::Escape($path)$share="\\$comp\$name"$wmi= gwmi Win32_LogicalFileSecuritySetting -filter"path='$path'"-ComputerName $comp$wmi.GetSecurityDescriptor().Descriptor.DACL | where {$_.AccessMask -as[Security.AccessControl.FileSystemRights]} |select ` @{name="Principal";Expression={"{0}\{1}"-f $_.Trustee.Domain,$_.Trustee.name}}, @{name="Rights";Expression={[Security.AccessControl.FileSystemRights]$_.AccessMask }}, @{name="AceFlags";Expression={[Security.AccessControl.AceFlags]$_.AceFlags }}, @{name="AceType";Expression={[Security.AccessControl.AceType]$_.AceType }}, @{name="ShareName";Expression={$share}} } gc serverlist.txt | foreach { if ($shares = Get-WmiObject Win32_Share -ComputerName $_ | Where {$_.Path}) { $shares | Foreach { Write-Progress -Status "Get share information on $($_.__Server)" $_.Name Get-NtfsRights $_.Name $_.Path $_.__Server} } else {"Failed to get share information from {0}." -f $($_.ToUpper())} } | ft Principal,Rights,AceFlags,AceType -GroupBy ShareName -Wrap | Out-File result.txt

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

Powershell script to show files that have been modified over 3 years old

$
0
0

I need to see how many files over 3 years have been modifed on a large file share and export it to a .csv file

Windows Server 2012 AD-DS can not be configured or uninistalled (Microsoft.Directory.Services.Deployment.DeepTasks.DeepTasks not found)

$
0
0

Good Afternoon everyone,

I am currently trying to promote my 2012 Server to a Domain Controller but when I am at the first step in the setup I get the Error Message

(German, Original Message):

[Bereitstellungskonfiguration] Fehler bei der Bestimmung, ob der Zielserver bereits ein Domänencontroller ist: Der Typ [Microsoft.Directory.Services.Deployment.DeepTasks.DeepTasks] wurde nicht gefunden: Vergewissern Sie sich, dass die Assembly, die diesen Typ enthält, geladen ist.

(Translated to English):

Error while determining, if the Targetserver already is a Domain Controller: The Type [Microsoft.Directory.Services.Deployment.DeepTasks.DeepTasks] was not found: Make sure, that the assembly, that contains this type, is loaded.

Thus I can neither Configure the AD-DS nor deinstall them via Server Manager. Any Help how to fix that problem would be greatly appricieated.


Pass Complex types as parameter in Remote powershell execution

$
0
0

Hi

    I am trying to pass a parameter to a remote script with an invoke-command.

    If i run the invoke command with the script in the local computer it´s works, but when i call the invoke-command with the second script in other server it´s fails with a conversion error for the type [System.Collections.Specialized.NameValueCollection]

    I think this can be because some serialization to transfer the data between the two servers. Any help??

   The command:

 Invoke-Command -computername $RemoteServerName -Credential $credential -Authentication Credssp -scriptblock {
       param(
            [String]$scriptDeploy,
            [String]$BackupPath,    
            [String]$DeployPath,
            [System.Collections.Specialized.NameValueCollection]$dtsConfigReplacements,
            [System.Collections.Specialized.NameValueCollection]$dtsxReplacements
            )  &"$scriptDeploy"  -BackupPath $BackupPath -DeployPath $DeployPath  -dtsConfigReplacements $dtsConfigReplacements  -dtsxReplacements $dtsxReplacements
         } -ArgumentList $Script_To_Run,  $script:BackupPath, $script:DeployPath, $script:dtsConfigReplacements,  $script:dtsxReplacements

    The command fails with this error:

Cannot process argument transformation on parameter 'dtsConfigReplacements'. Ca
 nnot convert the "System.Collections.ArrayList" value of type "System.Collectio
 ns.ArrayList" to type "System.Collections.Specialized.NameValueCollection".
 + CategoryInfo          : InvalidData: (:) [BDesarrollo.
 ps1], ParameterBindin...mationException
 + FullyQualifiedErrorId : ParameterArgumentTransformationError,Deploy.Aprovisionamiento.Desarrollo.ps1
 


Invoke remote comand line tool

$
0
0

I need to invoke a command line tool (imagine cmd or netsh) which can complete and return or remain interactive.

If I try Invoke-Command with cmd it returns without and error but doesn't remain interactive.

However, if I do it with my tool, I get this error:

Last compiled Sep 27 2012 07:53:09
  Port Number: 7188+ CategoryInfo          : NotSpecified: (:String) [], RemoteException+ FullyQualifiedErrorId : NativeCommandError+ PSComputerName        : MyServer
dlmcv - Copyright (C) 2011-2012, MyCorporation.
        All rights reserved

Is there a way to invoke and stay interactive?

How can I find out what this NativeCommandError was?


Paulo Morgado

Set-ADAccountPassword issues after password reset

$
0
0

I found a wonderful script that allows me to bulk reset users passwords using the set-adaccountpassword cmdlet.  The passwords change just fine but then when I set the user accounts to force a password change even if they are following the complexity requirements of our password policy they still cannot change their password.

I have even tested this out on a user account that wasn't changed by the cmdlet and it works fine, so it's following the password policy like it should.  I am assuming that the cmdlet changes some ad attributes on the user account but for the life of me can't fine which ones it changes.

I even went as far as to change our password policy so that it was more relaxed, turn off password memory and changed the number of required characters, and I amd still having the same issue.

The password that I used is an 8 character complex password and works for any other users that were not changed by the cmdlet.

Here is the script that I used, it's modified script that I found online possibly even in this forum: 

# import the AD module
if (-not (Get-Module ActiveDirectory)){     
 Import-Module ActiveDirectory -ErrorAction Stop
}   
# set new default password 
$password = ConvertTo-SecureString -AsPlainText "aaa4123!" -Force    
# get list of account names (1 per line) 
$list = Get-Content -Path c:\users\users.txt
# loop through the list 

ForEach ($u in $list) {       
 if ( -not (Get-ADUser -LDAPFilter "(sAMAccountName=$u)")) {          
  Write-Host "Can't find $u"
 }     
 else {
  $user = Get-ADUser -Identity $u        
  $user | Set-ADAccountPassword -NewPassword $password -Reset        
  $user | Set-AdUser -ChangePasswordAtLogon $false       
  Write-Host "changed password for $u"    
 } 

Here is the password policy that I am using:

PolicySetting
Minimum password length8 characters
Password must meet complexity requirementsEnabled
Store passwords using reversible encryptionDisabled
Account Policies/Account
Lockout Policy
PolicySetting
Account lockout threshold     5 invalid logon attempts
Account Policies/Kerberos
Policy
PolicySetting
Enforce user logon restrictionsEnabled
Maximum lifetime for service ticket600 minutes
Maximum lifetime for user ticket10 hours
Maximum lifetime for user ticket renewal7 days
Maximum tolerance for computer clock synchronization5 minutes

Any help on the would be great.


Adminstrative Center History

$
0
0

I understand that PS save the history per PS-session up to 32767 cmdlets. I know that i can export the history to a .xml file, but...

Where is the ADAC history saved?

I can see that the history is still there after a restart of a DC, so I presume that is imported from a .xml file.

I'm right or?

error in command line to do a wsus cleanup

$
0
0

Hi,

I wanted to make a script to automate cleaning of the wsus.  All my rules work quite good, just on (last) rule gives me a time-out. (i'm fairly new to scripting).  I've been looking to solve it but can't seem to find what the problem is.

The last line that gives the error is :   $CleanupManager.PerformCleanup($CleanupScope)

When i execute this line i get the following message :
Exception calling “PerformCleanup” with “1″ argument(s): “Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
The statement has been terminated.”
At line:1 char:31
+ $CleanupManager.PerformCleanup <<<< ($CleanupScope)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

I suggest that the cleanup is not executed then ?  How can i avoid the timeout ?
Any help would be appriciated.

Regards,
Jo

Powershell Script Quest One Snap-in Slow When Not Logged Into Domain

$
0
0

I have a powershell script that uses the Quest One ActiveRoles Management Shell for Active Directory snap-in.  

Scenario 1

When I'm in the office, the script runs very quickly (1 min).  No errors.

Scenario 2

When I take my laptop home, and log into the laptop using the same account (although I'm not connected to the domain), the script takes 20 minutes to complete.  No errors.

I have Internet access both at work and at home.

Script Code:

Function TestImport($a)
{
    Get-Date
    Write-Host "Importing CRL"
    $Q_CRL = Import-QADCertificateRevocationList -FileName $a
    Write-Host "Import Complete"
    $CRL_ThisUpdate = $Q_CRL.EffectiveDate
    $CRL_NextPublish = $Q_CRL.NextPublish
    $CRL_NextUpdate = $Q_CRL.NextUpdate
    Write-Host "CRL Effective Date/Time: $CRL_ThisUpdate"
    Write-Host "CRL Next Publish Date/Time: $CRL_NextPublish"
    Write-Host "CRL Next UPdate Date/Time: $CRL_NextUpdate"
    Get-Date
}

TestImport "C:\TEMP\My.CRL"

The slowness occurs when the script starts the import using the snap-in.

Get-PSSnapin returns the following:

Name        : Microsoft.PowerShell.Core
PSVersion   : 3.0
Description : This Windows PowerShell snap-in contains cmdlets used to manage components of Windows PowerShell.

Name        : Quest.ActiveRoles.ADManagement
PSVersion   : 1.0
Description : This Windows PowerShell snap-in contains cmdlets to manage Active Directory and Quest One ActiveRoles.

Get-ExecutionPolicy shows: RemoteSigned

Does anyone have any ideas as to why the snap-in would be running so slowly?  All the other parts of the script seem to run just fine; no slowness.  Any help would be greatly appreciated.

-m



wmi filter only works when negated twice

$
0
0

Has anyone ever saw this before and/or do they know whats causing it?  When i try to run the query with the filter of 10.1.% it doesn't return anything.  But when I negate the filter twice, I am actually getting the data I was looking for?!?! 

PS C:\> gwmi -Namespace root\microsoftdns microsoftdns_atype -Filter "IPaddress LIKE '10.1.%'" | Select IPAddress -First 10
PS C:\> gwmi -Namespace root\microsoftdns microsoftdns_atype -Filter "NOT NOT IPaddress LIKE '10.1.%'" | Select IPAddress -first 10

IPAddress
---------
10.1.91.3
10.1.91.4
10.1.91.1
10.1.91.5
10.1.91.6
10.1.91.2
10.1.27.45
10.1.27.41
10.1.72.9
10.1.27.61


PS C:\>


New-PSSession limited to 25

$
0
0

I am trying to start 50 sessions on a server, but once I pass 25 new sessions, I get this error:

New-PSSession : [MyServer] Connecting to remote server systemarchi failed with the following error message : The WS-
Management service cannot process the request. This user has exceeded the maximum number of concurrent shells allowed f
or this plugin. Close at least one open shell or raise the plugin quota for this user. For more information, see the ab
out_Remote_Troubleshooting Help topic.

WinRM settings:

Config
    MaxEnvelopeSizekb = 500
    MaxTimeoutms = 60000
    MaxBatchItems = 32000
    MaxProviderRequests = 4294967295
    Client
        NetworkDelayms = 5000
        URLPrefix = wsman
        AllowUnencrypted = false
        Auth
            Basic = true
            Digest = true
            Kerberos = true
            Negotiate = true
            Certificate = true
            CredSSP = false
        DefaultPorts
            HTTP = 5985
            HTTPS = 5986
        TrustedHosts
    Service
        RootSDDL = O:NSG:BAD:P(A;;GA;;;BA)(A;;GR;;;IU)S:P(AU;FA;GA;;;WD)(AU;SA;GXGW;;;WD)
        MaxConcurrentOperations = 4294967295
        MaxConcurrentOperationsPerUser = 1500
        EnumerationTimeoutms = 240000
        MaxConnections = 300
        MaxPacketRetrievalTimeSeconds = 120
        AllowUnencrypted = false
        Auth
            Basic = false
            Kerberos = true
            Negotiate = true
            Certificate = false
            CredSSP = false
            CbtHardeningLevel = Relaxed
        DefaultPorts
            HTTP = 5985
            HTTPS = 5986
        IPv4Filter = *
        IPv6Filter = *
        EnableCompatibilityHttpListener = false
        EnableCompatibilityHttpsListener = false
        CertificateThumbprint
        AllowRemoteAccess = true
    Winrs
        AllowRemoteShellAccess = true
        IdleTimeout = 7200000
        MaxConcurrentUsers = 10
        MaxShellRunTime = 2147483647
        MaxProcessesPerShell = 52
        MaxMemoryPerShellMB = 1024
        MaxShellsPerUser = 52

I have other servers, where i'm not limited to 25 sessions. Does anyone have a clue where to fix this?


Powershell script to compare AD UserObject Group Memberships in Excel

$
0
0

<#
CompareUserGroupMembershipsFromList.ps1
Powershell script to compare AD UserObject Group Memberships in Excel
[string](0..9|%{[char][int](32+("45737569004673677976").substring(($_*2),2))})-replace "\s{1}\b"
save list.txt file in same directory as script with sAMAccountNames (one per line), example follows:

CarlHungus
nio
morpheus
spock

#>
cls
function vars { get-variable | sort Name }
vars | remove-item #-whatif
$erroractionpreference = "SilentlyContinue"
Import-Module ActiveDirectory
$currentfolder = split-path $myinvocation.mycommand.path
$groups = ""
$userlist = GC $currentfolder\list.txt | sort
if (test-path $currentfolder\temp.txt) {remove-item $currentfolder\temp.txt}
if (test-path $currentfolder\MasterGroupList.txt) {remove-item $currentfolder\MasterGroupList.txt}
if (test-path $currentfolder\UserCNs.txt) {remove-item "$currentfolder\UserCNs.txt"}

Foreach ($user in $userlist)
    {
        $array = @() 
        $groups = Get-AdUser -Identity $user -property "MemberOf" 
        $sortedGroups = $groups.memberof | Sort | Get-Unique
            Foreach($group in $sortedGroups) 
            {$array +=$group} 
        $number = $array.count
        foreach ($item in $array)
        {      
         $1 = $item -replace "CN\=","" 
         $2 = $1 -replace "^*,OU\=.*$","" 
         $3 = $2 -replace "^*,Users.*$",""
         $4 = $3 -replace "^*,Builtin.*$",""
         add-content $currentfolder\temp.txt $4    
        }  
    }
$MasterGroupList = gc $currentfolder\temp.txt | sort | Get-Unique
remove-item $currentfolder\temp.txt
foreach ($schlub in $MasterGroupList) 
{add-content $currentfolder\MasterGroupList.txt $schlub}
# some Excel Constants 
# line styles 
$xlLineStyleNone = -4142 
$xlContinuous = 1 
$xlDash = -4115 
 
$a = New-Object -comobject Excel.Application
$a.Visible = $true
$functions = $a.WorkSheetfunction
$b = $a.Workbooks.Add()
$WS=$a.ActiveSheet
$cells = $WS.Cells
$date = Get-Date
#define some variables to control navigation
$row=1
$col=2
        $WS.UsedRange.Borders.LineStyle = $xlContinuous
        $blue = 255
        $green= 0
        $red = 0
        $a = 1
        $WS.UsedRange.Borders.Color = $a
        $WS.UsedRange.Borders.Weight = $xlThin
        $WS.Application.ActiveWindow.SplitColumn = 1
        $WS.Application.ActiveWindow.SplitRow = 1
        $WS.Application.ActiveWindow.FreezePanes=$true 
#insert column headings
GC $currentfolder\MasterGroupList.txt | foreach {
        $cells.item($row,$col)=$_
        $cells.item($row,$col).font.bold=$False
        $cells.item($row,$col).Orientation = 90
        $cells.EntireColumn.AutoFit() | Out-Null
        $WS.UsedRange.Borders.LineStyle = $xlContinuous
        $col++
    }
$row=2
$col=1
$blarb = Get-Content ("$currentfolder\list.txt") | Sort # 
foreach ($slarb in $blarb)
    {   
        $CN = Get-AdUser -filter 'SamAccountName -eq $slarb' 
        Add-Content "$currentfolder\UserCNs.txt" $CN
    }
$GroupList = @{} 
Function IsMember ($ADObject, $GroupName) 
    { 
        If ($GroupList.ContainsKey($ADObject.sAMAccountName.ToString() + "\") -eq $False) 
        { 
            $GroupList.Add($ADObject.sAMAccountName.ToString() + "\", $True) 
            $ADObject.psbase.RefreshCache("tokenGroups") 
            $SIDs = $ADObject.psbase.Properties.Item("tokenGroups") 
            ForEach ($Value In $SIDs) 
            { 
                $SID = New-Object System.Security.Principal.SecurityIdentifier $Value, 0 
                $Group = $SID.Translate([System.Security.Principal.NTAccount]) 
                $GroupList.Add($ADObject.sAMAccountName.ToString() + "\" + $Group.Value.Split("\")[1], $True) 
            } 
        } 
                If ($GroupList.ContainsKey($ADObject.sAMAccountName.ToString() + "\" + $GroupName)) {Return $True} 
                Else {Return $False } 
    } 
     $UserCNs = Get-Content("$currentfolder\UserCNs.txt") 
     foreach ($item in $UserCNs) 
        {  
            $User = [ADSI]"LDAP://$item" 
            $3 = $item -replace "CN\=","" 
            $4 = $3 -replace "^*,OU\=.*$",""
            $x=1
            $y=2
                   foreach ($habba in Get-content $currentfolder\MasterGroupList.txt)
                            {
                             If (IsMember $User $habba -eq $True) 
                                 {  write-host Yes,$habba,$User.sAMAccountName -Foregroundcolor green
                                    $cells.item($row,$col)=$4
                                    $cells.EntireColumn.AutoFit() | Out-Null
                                    $cells.item($row,$col).font.bold=$True
                                    $WS.Cells.Item($row,$y).Value() =1;$WS.Cells.Item($row,$y).Interior.ColorIndex = 34#;$WS.Cells.Item($row,$y).HorizontalAlignment = -4108
                                 }
                             Else
                                 {
                                    write-host No,$habba,$Computer.sAMAccountName -Foregroundcolor red
                                 }
                              $y++
                              $WS.UsedRange.Borders.LineStyle = $xlContinuous        
                            }
                   $Row++
         } 
if (test-path $currentfolder\MasterGroupList.txt) {remove-item $currentfolder\MasterGroupList.txt}
if (test-path $currentfolder\UserCNs.txt) {remove-item "$currentfolder\UserCNs.txt"}
  
  
  Function Convert-NumberToA1 
    { 

      Param([parameter(Mandatory=$true)] 
            [int]$number) 
 
      $a1Value = $null 
      While ($number -gt 0) { 
        $multiplier = [int][system.math]::Floor(($number / 26)) 
        $charNumber = $number - ($multiplier * 26) 
        If ($charNumber -eq 0) { $multiplier-- ; $charNumber = 26 } 
        $a1Value = [char]($charNumber + 64) + $a1Value 
        $number = $multiplier 
      } 
      Return $a1Value 
    }
  # End Function
 
Function xlSum 
        {
                $range = $WS.usedRange
                $rows  = $range.rows.count # Takes you to the last used row
                $cols   =  $range.columns.count # Takes you to the last used column
                $Sumrow = $rows + 1
                $Sumcol  = $cols + 1
                $Q=2
                $U=2
                        do
                            {
                                $Y=2
                                $p =  Convert-NumberToA1 ($Q)
                                $r = ("" + $p + $Y + ":" + $p + $rows)
                                write-host range $r
                                $derp = $WS.Range($r) 
                                write-host $Q$Sumrow
                                $WS.cells.item($SumRow,$Q) = $functions.sum($derp)
                                [void]$range.entireColumn.Autofit()
                                $Q++
                             }
                    while($Q -lt $Sumcol)
                        do
                            {
                                $G =  Convert-NumberToA1 ($cols)
                                $r = ("" + "B" + $U + ":" + $G + $U)
                                write-host range $r
                                $derp = $WS.Range($r) 
                                write-host $U$SumCol
                                $WS.cells.item($U,$Sumcol) = $functions.sum($derp)
                                [void]$range.entireColumn.Autofit()
                                $U++
                             }
                    while($U -lt $Sumrow)
                $WS.cells.item($SumRow,$SumCol) = $functions.sum($range)
                $cells.EntireColumn.AutoFit() | Out-Null
        } 
# End Function
        xlSum 
 #End Script


Powershell script to compare AD ComputerObject Group Memberships in Excel

$
0
0

<#
CompareComputerGroupMembershipsFromList.ps1
Powershell script to compare AD ComputerObject Group Memberships in Excel
[string](0..9|%{[char][int](32+("45737569004673677976").substring(($_*2),2))})-replace "\s{1}\b"
save list.txt file in same directory as script with ComputerNames (one per line), example follows:

comp1
comp2
comp3
comp4

#>
cls
function vars { get-variable | sort Name }
vars | remove-item #-whatif
$erroractionpreference = "SilentlyContinue"
Import-Module ActiveDirectory
$currentfolder = split-path $myinvocation.mycommand.path
$groups = ""
$computerlist = GC $currentfolder\list.txt | sort
if (test-path $currentfolder\temp.txt) {remove-item $currentfolder\temp.txt}
if (test-path $currentfolder\MasterGroupList.txt) {remove-item $currentfolder\MasterGroupList.txt}
if (test-path $currentfolder\computerCNs.txt) {remove-item "$currentfolder\computerCNs.txt"}

Foreach ($node in $computerlist)
    {
        $array = @() 
        $groups = Get-AdComputer -Identity $node -property "MemberOf" 
        $sortedGroups = $groups.memberof | Sort | Get-Unique
            Foreach($group in $sortedGroups) 
            {$array +=$group} 
        $number = $array.count
        foreach ($item in $array)
        {      
         $1 = $item -replace "CN\=","" 
         $2 = $1 -replace "^*,OU\=.*$","" 
         add-content $currentfolder\temp.txt $2    
        }  
    }
$MasterGroupList = gc $currentfolder\temp.txt | sort | Get-Unique
remove-item $currentfolder\temp.txt
foreach ($schlub in $MasterGroupList) 
{add-content $currentfolder\MasterGroupList.txt $schlub}
# some Excel Constants 
# line styles 
$xlLineStyleNone = -4142 
$xlContinuous = 1 
$xlDash = -4115 

$a = New-Object -comobject Excel.Application
$a.Visible = $true
$b = $a.Workbooks.Add()
$WS=$a.ActiveSheet
$cells = $WS.Cells
$date = Get-Date

#define some variables to control navigation
$row=1
$col=2
        $WS.UsedRange.Borders.LineStyle = $xlContinuous
        $blue = 255
        $green= 0
        $red = 0
        $a = 1
        $WS.UsedRange.Borders.Color = $a
        $WS.UsedRange.Borders.Weight = $xlThin
        $WS.Application.ActiveWindow.SplitColumn = 1
        $WS.Application.ActiveWindow.SplitRow = 1
        $WS.Application.ActiveWindow.FreezePanes=$true 
#insert column headings
GC $currentfolder\MasterGroupList.txt | foreach {
        $cells.item($row,$col)=$_
        $cells.item($row,$col).font.bold=$False
        $cells.item($row,$col).Orientation = 90
        $cells.EntireColumn.AutoFit() | Out-Null
        $WS.UsedRange.Borders.LineStyle = $xlContinuous
        $col++
    }
$row=2
$col=1
$blarb = Get-Content ("$currentfolder\list.txt") | Sort | Get-Unique
foreach ($slarb in $blarb)
    {   
        $CN = Get-AdComputer -Identity $slarb 
        Add-Content "$currentfolder\computerCNs.txt" $CN
    }
$GroupList = @{} 
Function IsMember ($ADObject, $GroupName) 
    { 
        If ($GroupList.ContainsKey($ADObject.sAMAccountName.ToString() + "\") -eq $False) 
        { 
            $GroupList.Add($ADObject.sAMAccountName.ToString() + "\", $True) 
            $ADObject.psbase.RefreshCache("tokenGroups") 
            $SIDs = $ADObject.psbase.Properties.Item("tokenGroups") 
            ForEach ($Value In $SIDs) 
            { 
                $SID = New-Object System.Security.Principal.SecurityIdentifier $Value, 0 
                $Group = $SID.Translate([System.Security.Principal.NTAccount]) 
                $GroupList.Add($ADObject.sAMAccountName.ToString() + "\" + $Group.Value.Split("\")[1], $True) 
            } 
        } 
                If ($GroupList.ContainsKey($ADObject.sAMAccountName.ToString() + "\" + $GroupName)) {Return $True} 
                Else {Return $False } 
    } 
     $computerCNs = Get-Content("$currentfolder\ComputerCNs.txt") 
     foreach ($item in $computerCNs) 
        {  
            $Computer = [ADSI]"LDAP://$item" 
            $3 = $item -replace "CN\=","" 
            $4 = $3 -replace "^*,OU\=.*$",""
            $x=1
            $y=2
                   foreach ($habba in Get-content $currentfolder\MasterGroupList.txt)
                            {
                             If (IsMember $Computer $habba -eq $True) 
                                 {  write-host Yes,$habba,$Computer.sAMAccountName -Foregroundcolor green
                                    $cells.item($row,$col)=$4
                                    $cells.EntireColumn.AutoFit() | Out-Null
                                    $cells.item($row,$col).font.bold=$True
                                    $WS.Cells.Item($row,$y).Value() =1;$WS.Cells.Item($row,$y).Interior.ColorIndex = 34 
                                 }
                             Else
                                 {
                                    write-host No,$habba,$Computer.sAMAccountName -Foregroundcolor red
                                 }
                              $y++
                              $WS.UsedRange.Borders.LineStyle = $xlContinuous        
                            }
                   $Row++
         } 
if (test-path $currentfolder\MasterGroupList.txt) {remove-item $currentfolder\MasterGroupList.txt}
if (test-path $currentfolder\computerCNs.txt) {remove-item "$currentfolder\computerCNs.txt"}

 
  Function Convert-NumberToA1 
    { 

      Param([parameter(Mandatory=$true)] 
            [int]$number) 
 
      $a1Value = $null 
      While ($number -gt 0) { 
        $multiplier = [int][system.math]::Floor(($number / 26)) 
        $charNumber = $number - ($multiplier * 26) 
        If ($charNumber -eq 0) { $multiplier-- ; $charNumber = 26 } 
        $a1Value = [char]($charNumber + 64) + $a1Value 
        $number = $multiplier 
      } 
      Return $a1Value 
    }
  # End Function
 
Function xlSum 
        {
                $range = $WS.usedRange
                $rows  = $range.rows.count # Takes you to the last used row
                $cols   =  $range.columns.count # Takes you to the last used column
                $Sumrow = $rows + 1
                $Sumcol  = $cols + 1
                $Q=2
                $U=2
                        do
                            {
                                $Y=2
                                $p =  Convert-NumberToA1 ($Q)
                                $r = ("" + $p + $Y + ":" + $p + $rows)
                                write-host range $r
                                $derp = $WS.Range($r) 
                                write-host $Q$Sumrow
                                $WS.cells.item($SumRow,$Q) = $functions.sum($derp)
                                [void]$range.entireColumn.Autofit()
                                $Q++
                             }
                    while($Q -lt $Sumcol)
                        do
                            {
                                $G =  Convert-NumberToA1 ($cols)
                                $r = ("" + "B" + $U + ":" + $G + $U)
                                write-host range $r
                                $derp = $WS.Range($r) 
                                write-host $U$SumCol
                                $WS.cells.item($U,$Sumcol) = $functions.sum($derp)
                                [void]$range.entireColumn.Autofit()
                                $U++
                             }
                    while($U -lt $Sumrow)
                $WS.cells.item($SumRow,$SumCol) = $functions.sum($range)
                $cells.EntireColumn.AutoFit() | Out-Null
        } 
# End Function
        xlSum 
 #End Script


PS script to detect Windows version in GPO logon

$
0
0

I've been looking for a way to exclude Windows 7 machines from a GPO logon script that substitutes a local drive letter on our PCs.  The Group Policy Management Editor has a tab for PowerShell scripts and I'm thinking I might be able to choose from'For this GPO, run scripts in the following order - Run Windows Powershell Scripts Last'to undo the original script's commands specifically for Win 7 PCs.

I've never written a PS script before so I'm researching how to do this, but if anyone has any suggestion for what I imagine would be a pretty simple script, I'd appreciate it :) 

The original script is a .cmd file

@echo off
cd\
cls
subst o: c:\Windows
Exit

Basically the PS script would need to undo this for W7 machines.

 

NIC Teaming Script Using New-NetLbfoTeam

$
0
0
Hi,

I am trying to make a NIC team using a powershell script with the cmdlet New-NetLbfoTeam on a Physical Windows Server 2012 Server Core.

When i execute the command PS C:\> New-NetLbfoTeam -Name Public -TeamMembers "Public 1", "Public 2" i get the result i want in the output below.

Confirm
Are you sure you want to perform this action?
Creates Team:'Public' with TeamMembers:{'Public 1', 'Public 2'},
TeamNicName:'Public', TeamingMode:'SwitchIndependent' and
LoadBalancingAlgorithm:'TransportPorts'.
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help


When i put the same New-NetLbfoTeam line in a powershell script and execute it i get awrong TeamNicName (see output blow)

Confirm
Are you sure you want to perform this action?

Creates Team:'â?Name Public â?TeamMembers' with TeamMembers:{'Public 1','Public 2'},
TeamNicName:'â?Name Public â?TeamMembers',
TeamingMode:'SwitchIndependent' and LoadBalancingAlgorithm:'TransportPorts'.
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help


Any experience with this issue?
Thanks in advance,

Wout



Viewing all 21975 articles
Browse latest View live