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

indexing two arrays in Powershell

$
0
0

Hi All,

I try to index two arrays by matching values;

I have Inventory of computer names with AD last logon date, I want to update lastlogon date column with new arrays lastlogon date column

I tried to use below script, I don't get any error but its not updating Inventory array.

Any Idea...

ForEach($newad in $newads)
{
    ForEach($Inventory in $Inventorys)
      {           
        If($newad.name -eq $Inventory.All_Workstations)
          {
            $Inventory.AD_lastlogondate = $newad.lastlogondate
          }
      }
  }

$Inventory
All_WorkstationsAD_lastlogondate
Computer105/06/2019
Computer206/06/2019
Computer307/06/2019
Computer408/06/2019
Computer509/06/2019
Computer610/06/2019
Computer711/06/2019


$newad
Namelastlogondate
Computer109/07/2019
Computer209/07/2019
Computer309/07/2019
Computer409/07/2019
Computer509/07/2019



Powershell Users in a Group list and then export users recursive

$
0
0

Hi,
I am wanting to find out how to put the two together. I have the following script for finding users/groups that have access to certain folders.

$project_folder = "\\UNC PATH"
get-acl $project_folder | %{ $_.Access  } | ft -property IdentityReference, AccessControlType, FileSystemRight

and then the following for finding AD Groupmembers with the recursive parameter

Get-ADgroupmember -identity “ADGroupmember” -Recursive | get-aduser -property displayname | select name, displayname >C:\output\Members.txt

How can I put the two together so I get a list of all users/groups by using the first script to list them and then list all the users in that are in any groups to a txt file...

PS - Powershell noob.


Thanks

PowerShell Script to Find AD Users with Extension Attribute 6 set

$
0
0

Could someone assist me in creating a PowerShell Script to search AD for Users that have Attribute 6 Set or modified from the Default <not set> status and export this list to Text file or .xls?

Any help would be greatly appreciated.


JustHangingOn

Add-ADGroupMember : A referral was returned from the server???

$
0
0

I'm sure I'm missing something here...

All I want to do is add a user from a child domain to a universal distribution group in a parent domain.  Sounds simple enough right?  WRONG!

Here is the example that the help gives:

-------------------------- EXAMPLE 4 --------------------------
    C:\PS>$user = Get-ADUser "CN=Glen John,OU=UserAccounts,DC=NORTHAMERICA,DC=FABRIKAM,DC=COM" -Server "northamerica.fabrikam.com";
    $group = Get-ADGroup "CN=AccountLeads,OU=UserAccounts,DC=EUROPE,DC=FABRIKAM,DC=COM -Server "europe.fabrikam.com";
    Add-ADGroupMember $group -Member $user -Server "europe.fabrikam.com"
    Description
    -----------
    Adds the user "CN=Glen John,OU=UserAccounts" from the North America domain to the group "CN=AccountLeads,OU=UserAccounts" in the Europe domain.



What I can gather from this is that what I am trying to accomplish SHOULD be possible however I'm missing something critical.  Here is the command I'm trying to run:

Add-ADGroupMember -Identity "CN=Test-Group,OU=Area 51,DC=rootdomain,DC=int" -Members "CN=Homer Simpson,OU=TEST,DC=childdomain,DC=rootdomain,DC=int"

And here is the Error that I'm getting:

Add-ADGroupMember : A referral was returned from the server
At line:1 char:1+ Add-ADGroupMember -Identity "CN=Test-Group,OU=Area 51,DC=rootdomain,DC=int ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : ResourceUnavailable: (CN=Test-Grou...DC=rootdomain,DC=int:ADGroup) [Add-ADGroupMember], ADReferralException+ FullyQualifiedErrorId : ActiveDirectoryServer:8235,Microsoft.ActiveDirectory.Management.Commands.AddADGroupMember

I've tried adding the:

  • -Server "dc01.rootdomain.int:3268"
  • -Server "rootdomain.int:3268"
  • -Server "rootdomain.int"
  • -Server "dc01.childdomain.rootdomain.int:3268"
  • -Server "childdomain.rootdomain.int:3268"
  • -Server "childdomain.rootdomain.int"

I am logged in as an Enterprise administrator however one of the next things I'm going to try is to pass my credentials to the command.  Any thoughts as to what might be going on?

Active Directory Account Expiration Notification to Managers

$
0
0

Active Directory Account Expiration Notification to Managers

Hello script gurus - I wanted to send an automatic email notification to managers pertaining to their contractors that has an end date on their AD accounts. The script that I found had most of the features I'm looking for. However need assistance on how to add the following into the script.

- Add additional message into the body of the email.
- Exclude the "past" expired accounts from the report.

When the report runs it sends the email to managers just fine however, we've noticed that it is including the ones that are already expired. We want to only send the ones that are expiring within 30 days from this date forward.  


Here's the script I found referenced in this forum:
https://social.technet.microsoft.com/Forums/windows/en-US/9d080c24-b2a2-4d9b-b50b-ca7fb9d95a91/account-expiration-email-notification?forum=winserverpowershell&prof=required 

Thank you for your time and appreciate any assistance!

Cheers.

Get-ADUser -Filter * -Properties directReports,EmailAddress | ForEach {

    $body = @()

    If ($_.directReports) {

        $managerEmailAddress = $_.EmailAddress

        $_.directReports | ForEach {

            $userDetails = Get-ADUser $_ -Properties AccountExpirationDate

            If ( $userDetails.AccountExpirationDate ) {

                If ( $userDetails.AccountExpirationDate -lt (Get-Date).AddDays(30) ) {

                    $sendEmail = $true

                    $props = [ordered]@{
                        Username=$userDetails.SamAccountName
                        'Account Expiration Date'=$userDetails.AccountExpirationDate
                    }

                    $body += New-Object PsObject -Property $props

                }
            }

        }

    }

    If ($sendEmail) {

        $body = $body | Out-String

        Send-MailMessage -From 'email@domain.com' -To $managerEmailAddress -Subject 'Account Expiration Report' -Body $body -SmtpServer 'mail.domain.com'

    }

    $sendEmail = $false

}

# Generic check for users with no manager
$bodyNM = @()
Get-ADUser -Filter * -Properties AccountExpirationDate,Manager | ForEach {

    If ( !$_.Manager ) {

        If ( $_.AccountExpirationDate) {

            If ($_.AccountExpirationDate -lt (Get-Date).AddDays(30) ) {

                $sendEmailNM = $true

                $propsNM = [ordered]@{
                    Username=$_.SamAccountName
                    'Account Expiration Date'=$_.AccountExpirationDate
                }

                $bodyNM += New-Object PsObject -Property $propsNM       

            }

        }

    }

}

If ($sendEmailNM) {

    $bodyNM = $bodyNM | Out-String
    Send-MailMessage -From 'email@domain.com' -To 'helpdesk@domain.com' -Subject 'Account Expiration Report' -Body $bodyNM -SmtpServer 'mail.domain.com'

}

                            

Cheers, DB

How to export AD user and AD groups into Excel in matrix format

$
0
0

Hi 

Could anyone please tell me how to export AD users and AD group into Excel file. Something like  usernames in rows and Groups in the column. I am looking for a excel which shows everything in one page.

Thank you in advance


Shekar-Technet

Get remote logged on user with powershell

$
0
0

Hi

I'm looking to get the name of the currently logged on user of a remote pc.    Im not going to use anything that changes the environment such as setting up invoke-command, psremoting etc. 

There is a dos command query.exe   but id prefer an object returned so I can get the info directly.

I did see a module called PSTerminalServices  and imported this, it worked ok but only for some computers!

I received an error when running the same command on others   "Get-TSSession -ComputerName "$computer"

Exception calling "GetSessions" with "0" argument(s): "Access is denied"
At C:\Users\bicard\Documents\WindowsPowerShell\Modules\PSTerminalServices\PSTerminalServices.psm1:219 char:6
+                     $session = $TSRemoteServer.GetSessions()

I have a domain admin account and these are domained machines so permissions are not an issue.

I have checked the remote machine and see that it does allow remote desktop connections

Ive checked the website for the module and searched the internet so feel I may need to abandon  the Get-TSSession   route as I need to know 100%  that it will work with each machine and I cant find if im doing something wrong, the same error has cropped up on the net but I never seen a solution.

I'm wondering has anyone encountered this module with that error or know of another way of getting the currently logged on user of a remote computer ?

My next plan was to go down the psexec.exe route but want to keep the code all powershell if I can.

Thanks

Confuseis


confuseis



Need to run with different user

$
0
0

Hello,

I want to run powershell script with different user account. And i need to store/save those account details as i need to run every time with that account.

Can you please suggest.

Thank You,

Avis


SharePoint 2010 get list of site owners

$
0
0

Need a powershell script that will loop through all sites and subsites in a site collection that will get all owners with Full Control permissions.

The reports should provide the following

  • The URL of the site with users with Full Control
  • The URL of the Parent Site if it is a subsite
  • Names of the Site Owners of the Parent

I have researched numerous boards and scripts provided are either incomplete or do not even work.
So if you respond and send me a link to another site please make sure it actually works.

Installing webserver on Windows 10 Build 1803 - Powershell Script

$
0
0

Hi,

I am building a developers windows 10 machine who use .NET, Visual C++ and other softwares. They need to have IIS installed on Windows 10 machine. We have a ps script that runs to install these features on Windows Server 2016. I am trying to run this script on the Windows 10 machine. It gives me an error 

Add-WindowsFeature : The term 'Add-WindowsFeature' is not recognized as the name of a cmdlet, ...................

So, I went and tried and did a "Import-module servermanager"

and it is not able to to load the servermanager since no valid module file was found in any module directory. How can I go about getting this installed. Here is the script shown below that I am trying to run on a Windows 10 machine.




AA2913

Reusing a function

$
0
0

I want to reuse a function, first to browse out to a source folder and then again to browse out to the target folder.  Guess I just don't understand and could use some help.  Here is the script:

function Find-Folders {
    param ($Folder)
    [Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
    [System.Windows.Forms.Application]::EnableVisualStyles()
    $browse = New-Object System.Windows.Forms.FolderBrowserDialog
    $browse.SelectedPath = "C:\"
    $browse.ShowNewFolderButton = $True
    $browse.Description = "Select a " + $Folder + " folder"

    $loop = $true
    while($loop)
    {
        if ($browse.ShowDialog() -eq "OK")
        {
        $loop = $false
		Write-Host "Your source is " $Folder
        } else
        {
            $res = [System.Windows.Forms.MessageBox]::Show("You clicked Cancel. Would you like to try again or exit?", "Select a location", [System.Windows.Forms.MessageBoxButtons]::RetryCancel)
            if($res -eq "Cancel")
            {
                #Ends script
                return
            }
        }
    }
    $browse.SelectedPath
    $browse.Dispose()
}

Find-Folders Source

Find-Folders Target

I need to save the results of the function to a $sourceFolder variable and then to a $targetFolder variable, to reuse in a copy-item command.

Hope someone can help and thanks in advance.

specific AD rights delegation

$
0
0

I'm looking for the commands to control AD delegation via a powershell script which I can find a few examples on how to set full rights to an OU as an example but nothing on how to set specific rights.

I don't know where to begin in explaining this but I have a script function I have tried to figure out with no luck.

Here are the rights I need to add to an assortment (roughly 100) of OU locations:

Reset password
Read/Write lockouttime
Read/Write pwdlastset
Read/Write UserAccountcontrol
Write Account Restrictions
Read MemberOf

I used the GUI to set these on a test OU and then ran get-acl and came up with this:

ActiveDirectoryRightsInheritanceTypeObjectTypeInheritedObjectTypeObjectFlagsAccessControlTypeIdentityReferenceIsInheritedInheritanceFlagsPropagationFlags


ReadProperty, WriteProperty Descendents 28630ebf-41d5-11d1-a9c1-0000f80367c1 bf967aba-0de6-11d0-a285-00aa003049e2 ObjectAceTypePresent, InheritedObjectAceTypePresent Allow AD\DelGroup-SG FALSE ContainerInherit InheritOnly ReadProperty, WriteProperty Descendents bf967a68-0de6-11d0-a285-00aa003049e2 bf967aba-0de6-11d0-a285-00aa003049e2 ObjectAceTypePresent, InheritedObjectAceTypePresent Allow AD\DelGroup-SG FALSE ContainerInherit InheritOnly ReadProperty, WriteProperty Descendents bf967a0a-0de6-11d0-a285-00aa003049e2 bf967aba-0de6-11d0-a285-00aa003049e2 ObjectAceTypePresent, InheritedObjectAceTypePresent Allow AD\DelGroup-SG FALSE ContainerInherit InheritOnly ReadProperty, WriteProperty Descendents 4c164200-20c0-11d0-a768-00aa006e0529 bf967aba-0de6-11d0-a285-00aa003049e2 ObjectAceTypePresent, InheritedObjectAceTypePresent Allow AD\DelGroup-SG FALSE ContainerInherit InheritOnly ReadProperty Descendents bf967991-0de6-11d0-a285-00aa003049e2 bf967aba-0de6-11d0-a285-00aa003049e2 ObjectAceTypePresent, InheritedObjectAceTypePresent Allow AD\DelGroup-SG FALSE ContainerInherit InheritOnly ExtendedRight Descendents 00299570-246d-11d0-a768-00aa006e0529 bf967aba-0de6-11d0-a285-00aa003049e2 ObjectAceTypePresent, InheritedObjectAceTypePresent Allow AD\DelGroup-SG FALSE ContainerInherit InheritOnly

Here is an example script I was trying to use figure out how to use.  This is from ITforDummies.net

https://itfordummies.net/2017/05/15/active-directory-delegation-powershell/

Function Grant-ADPermission{ <# 
     .SYNOPSIS 
        Add Access Control Entry on Active Directory Organizational Unit.      .DESCRIPTION 
        This function will create ACE and add them to the specified AD OU's. 
     .EXAMPLE 
         Grant-ADPermission -GroupDistinguishedName 'CN=Applications2,OU=Groups,DC=D2K12R2,DC=local' -AdRights WriteProperty -AccessControlType Allow -Inheritance Children -ObjectType user -InheritedObjectType user -OrgUnitDN 'OU=Test,DC=D2K12R2,DC=local' 
     .EXAMPLE 
         Grant-ADPermission -GroupDistinguishedName 'CN=StarWars-Computers_CreateDelete,OU=Groups,OU=Admins,DC=D2K8R2,DC=itfordummies,DC=net' -AdRights CreateChild,DeleteChild -AccessControlType Allow -Inheritance Children -OrgUnitDN 'OU=Computers,OU=Star Wars,OU=Production,DC=D2K8R2,DC=itfordummies,DC=net' -ObjectType computer -InheritedObjectType null -Verbose 
     .EXAMPLE 
        'OU=lvl2,OU=Test,DC=D2K12R2,DC=local','OU=Trash,OU=Test,DC=D2K12R2,DC=local' | Grant-ADPermission -GroupDistinguishedName 'CN=Applications2,OU=Groups,DC=D2K12R2,DC=local' -AdRights WriteProperty -AccessControlType Allow -Inheritance Children -ObjectType user -InheritedObjectType user 
     .PARAMETER GroupDistinguishedName 
         DistinguishedName of the group to give permission to. 
     .PARAMETER AdRights 
         System.DirectoryServices.ActiveDirectoryRights, autocompletion should work from PS3+. 
     .PARAMETER AccessControlType 
        System.Security.AccessControl.AccessControlType, autocompletion should work from PS3+. 
    .PARAMETER Inheritance 
         System.DirectoryServices.ActiveDirectorySecurityInheritance, autocompletion should work from PS3+. 
     .PARAMETER OrgUnitDN 
         String[] containing the list of OU to delegate. You can specify more than one, and use pipeline input. 
     .PARAMETER InheritedObjectType 
         Dynamic param containing LDAPName of all schema objects. The function will use the associated GUID. 
    .PARAMETER ObjectType 
         Dynamic param containing LDAPName of all schema objects. The function will use the associated GUID. 
     .INPUTS 
     .OUTPUTS 
     .NOTES 
         Uses Dynamic Parameters. 
     .LINK 
         http://ItForDummies.net 
     #> 
     [CmdletBinding()] 
     Param( 
         [Parameter(Mandatory = $true)] 
         [String]$GroupDistinguishedName, 
         [Parameter(Mandatory = $true)] 
         [System.DirectoryServices.ActiveDirectoryRights[]]$AdRights, 
         [Parameter(Mandatory = $true)] 
         [System.Security.AccessControl.AccessControlType]$AccessControlType, 
         [Parameter(Mandatory = $true)] 
         [System.DirectoryServices.ActiveDirectorySecurityInheritance]$Inheritance, 
         [Parameter(Mandatory = $true, 
             ValueFromPipeline=$true, 
             ValueFromPipelineByPropertyName=$true)] 
         [String[]]$OrgUnitDN, 
         [Switch]$PassThru 
     ) 
     DynamicParam{ 
         #region ObjectType 
         # Set the dynamic parameters' name 
         $ParameterName = 'ObjectType' 
         # Create the dictionary  
        $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary 
         # Create the collection of attributes 
         $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] 
         # Create and set the parameters' attributes 
         $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute 
         $ParameterAttribute.Mandatory = $true 
         $ParameterAttribute.Position = 1 
         # Add the attributes to the attributes collection 
         $AttributeCollection.Add($ParameterAttribute) 

         # Generate and set the ValidateSet 
        $DomainName = [DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name 
         $MasterGuidMap = @{} 
         $SchemaGuidMapSearcher = [ADSISearcher]'(schemaidguid=*)' 
         $SchemaGuidMapSearcher.SearchRoot = [ADSI]"LDAP://CN=Schema,$(([ADSI]"LDAP://$DomainName/RootDSE").configurationNamingContext)" 
         $null = $SchemaGuidMapSearcher.PropertiesToLoad.AddRange(('ldapdisplayname','schemaidguid')) 
         $SchemaGuidMapSearcher.PageSize = 10000 
        $SchemaGuidMapSearcher.FindAll() | Foreach-Object -Process { 
            #$MasterGuidMap[(New-Object -TypeName Guid -ArgumentList (,$_.properties.schemaidguid[0])).Guid] = "$($_.properties.ldapdisplayname)" 
            $MasterGuidMap["$($_.properties.ldapdisplayname)"] = (New-Object -TypeName Guid -ArgumentList (,$_.properties.schemaidguid[0])).Guid 
         } -End {$MasterGuidMap['null'] = [Guid]'00000000-0000-0000-0000-000000000000'} 
         $DynamicParamValue = $MasterGuidMap.Keys 

 
         #$DynamicParamValue 
         $ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($DynamicParamValue) 
 
 
         # Add the ValidateSet to the attributes collection 
         $AttributeCollection.Add($ValidateSetAttribute) 
 
 
        # Create and return the dynamic parameter 
        $RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection) 
        $RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter) #ForEach DynamicParam 
         #endregion 
 
 
         #region InheritedObjectType 
         #Second DynParam 
         # Set the dynamic parameters' name 
        $ParameterName = 'InheritedObjectType' 
              
         # Create the dictionary  
         #$RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary #Already created 

 
         # Create the collection of attributes 
        $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] 
              
         # Create and set the parameters' attributes 
         $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute 
        $ParameterAttribute.Mandatory = $true 
         $ParameterAttribute.Position = 1 
 
 
         # Add the attributes to the attributes collection 
         $AttributeCollection.Add($ParameterAttribute) 
 
 
        # Generate and set the ValidateSet 
        #$DomainName = [DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name 
         #$MasterGuidMap = @{} 
         $RightsGuidMapSearcher = [ADSISearcher]'(&(objectclass=controlAccessRight)(rightsguid=*))' 
         $RightsGuidMapSearcher.SearchRoot = [ADSI]"LDAP://CN=Schema,$(([ADSI]"LDAP://$DomainName/RootDSE").configurationNamingContext)" 
         $null = $RightsGuidMapSearcher.PropertiesToLoad.AddRange(('displayname','rightsGuid')) 
         $RightsGuidMapSearcher.PageSize = 10000 
         $RightsGuidMapSearcher.FindAll() | Foreach-Object -Process { 
            #$MasterGuidMap[(New-Object -TypeName Guid -ArgumentList (,$_.properties.rightsguid[0])).Guid] = "$($_.properties.displayname)" 
             $MasterGuidMap["$($_.properties.displayname)"] = (New-Object -TypeName Guid -ArgumentList (,$_.properties.rightsguid[0])).Guid 
         } -End {$MasterGuidMap['null'] = [Guid]'00000000-0000-0000-0000-000000000000'} 
         $DynamicParamValue = $MasterGuidMap.Keys 
         #$DynamicParamValue 
         $ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($DynamicParamValue) 
         # Add the ValidateSet to the attributes collection 
         $AttributeCollection.Add($ValidateSetAttribute) 
         # Create and return the dynamic parameter 
         $RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection) 
         $RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter) #ForEach DynamicParam 
         #endregion 
         #Output 
         $RuntimeParameterDictionary 
     } 
     Begin{ 
         #Dynamic Param 
         $PsBoundParameters.GetEnumerator() | ForEach-Object -Process { New-Variable -Name $_.Key -Value $_.Value -ErrorAction 'SilentlyContinue' } 
         #Prepare the Access Control Entry, force the type for constructor binding 
         Write-Verbose -Message 'Preparing Access Control Entry attributes...' 
         [System.Security.Principal.SecurityIdentifier]$Identity = (New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList $(([ADSI]"LDAP://$GroupDistinguishedName").ObjectSid), 0).value #Get nice SID format 
         [Guid]$InheritedObjectTypeValue = $MasterGuidMap[$InheritedObjectType] 
         [Guid]$ObjectTypeValue          = $MasterGuidMap[$ObjectType] 
         #Create the Access Control Entry 
         Write-Verbose -Message 'Creating Access Control Entry...' 
         $NewAce = New-Object System.DirectoryServices.ActiveDirectoryAccessRule -ArgumentList $Identity,$AdRights,$AccessControlType,$ObjectTypeValue,$Inheritance,$InheritedObjectTypeValue 
     } 
     Process{ 
         try{ 
             Write-Verbose -Message "Connecting to $OrgUnitDN" 
             $ADObject = [ADSI]("LDAP://" + $OrgUnitDN) 
             $ADObject.ObjectSecurity.AddAccessRule($NewAce) 
             Write-Verbose -Message 'Applying Access Control Entry' 
             $ADObject.CommitChanges() 
             if($PassThru){ 
                 $ADObject.ObjectSecurity.Access 
             } 
         } 
         catch{ 
             throw "$OrgUnitDN $_" 
         } 
     } 
     End{} 
 } 

$OU = "OU=Users,OU=Admin,DC=AD,DC=com","OU=Users,OU=Admin2,DC=AD,DC=com"



foreach ($OUs in $OU)
{
 Grant-ADPermission -GroupDistinguishedName 'CN=DelGroup-SG,OU=Groups,DC=AD,DC=com' -AdRights GenericAll -AccessControlType Allow -Inheritance All -OrgUnitDN $OUs -ObjectType user -InheritedObjectType user -Verbose
 }

But this grants full access instead of the specific rights needed.  Can anyone help???



Remove Terminated Users Mobile Devices from O365

$
0
0

Hey all,

So i am new to using power shell and trying to make part of our termination process less manual. Right now I have a powershell script that sets a users out of office from information pulled from a CSV. I am trying to take this one step further by also removing any mobile device associated with their account. The issue I am running into is how to call the identity of the associated devices per user and then pump that data back into the script all at once. I just cant seem to get the syntax or commands rights.

Ideally it would be something like this;

User1@company.com

Device1

Device2

Script to set user1@company.com OOO > get list of mobile devices > returns Device1 and Device2 > Remove Device1 and Device2 > goes on to next user and repeats process.

PowerShell script to get - disk uniqueID and drive letter

$
0
0

Hi

I am new to PowerShell and just started to learn it. Your help is much appreciated on this.

In our environment, we frequently expand the server's disks. For that we need to get disk's unique ID and drive letter of servers (VM, VM with RDMs, Physical server). I am able to get this on the server by running the following PowerShell cmdlet and referring the number in Disk management (diskmgmt.msc).

get-disk | Select number, uniqueid
However, I find this a bit of manual work and want to obtain both drive letter and unique ID from a central server (say ex: Jumpbox) via PowerShell.

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

I find one script and that able to fetches the drive letter and unique ID. However, I find the script does not work if the VM contains RDMs or if it is a physical server.

http://blog.tenera.no/?p=220

$strComputer = Read-host -prompt 'Enter the server name:'
$colDiskDrives = get-wmiobject -query "Select * From Win32_DiskDrive" -computer $strComputer

$allDrive = @()

 Foreach ($drive in $colDiskDrives)
     {
         $o_drive = New-Object PSObject
         $a = $drive.DeviceID.Replace("\", "\\")

         if($drive.serialnumber -ne $null)
             {
                 $o_drive | Add-Member -type NoteProperty -Name UUID -value $drive.SerialNumber
                 $colPartitions = get-wmiobject -query "Associators of {Win32_DiskDrive.DeviceID=""$a""} WHERE AssocClass = Win32_DiskDriveToDiskPartition" -computer $strComputer
                 Foreach ($Partition in $colPartitions)
                 {
                     $b = $Partition.DeviceID
                     $colLogicalDisk = get-wmiobject -query "Associators of {Win32_DiskPartition.DeviceID=""$b""} WHERE AssocClass = Win32_LogicalDiskToPartition" -computer $strComputer

                     If ($colLogicalDisk.Caption -ne $null)
                         {
                             $o_drive | Add-Member -type NoteProperty -Name DriveLetter -value $colLogicalDisk.Caption.ToString()
                         }
                     Else
                         {
                             #No letter assigned.
                         }
                 }
             }
         else
         {
             #No UUID found.
         }

     $allDrive += $o_drive
     }
 $allDrive

there is also one more thing in Stackoverflow on similar topic. However, this does not contain disk unique id:

https://stackoverflow.com/questions/31088930/combine-get-disk-info-and-logicaldisk-info-in-powershell

Get-CimInstance Win32_Diskdrive -PipelineVariable disk |
Get-CimAssociatedInstance -ResultClassName Win32_DiskPartition -PipelineVariable partition |
Get-CimAssociatedInstance -ResultClassName Win32_LogicalDisk |
Select-Object @{n='Disk';e={$disk.deviceid}},
@{n='DiskSize';e={$disk.size}},
@{n='DiskModel';e={$disk.model}},
@{n='Partition';e={$partition.name}},
@{n='RawSize';e={$partition.size}},
@{n='DriveLetter';e={$_.DeviceID}},
VolumeName,Size,FreeSpace
Please let me know how to get drive letter and disk UID for VM, VM with RDMs, Physical server etc. Your help is much appreciated. Thanks in advance.

Azure AZ modules not working while nested in functions

$
0
0

Hello,

I have written some complex PowerShell scripts for reuse.  I am cleaning them up and compartmentalizing into functions for readability, etc.

I am having trouble with AZ functions not working inside of nested functions.  Maybe this is by design and a normal feature of PowerShell but if so it's not one that I understand yet.

The module works fine.

If I call the module from a function it works fine

If I call the function with the module from another function it just doesn't work.  It doesn't do anything.  There's no error to catch, the whole response object is just the fully qualified name of the method.

Get-AzProviderFeature is the module function I'm calling.

It works fine.  It works fine inside of a function. If I call that function from another function then the whole result is

Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkModels.PSProviderFeature

I'm sure this is a 101 newbie nuance thing and not a problem with Azure modules but I'm still stuck.

I'm wondering if the AzContext or AzLogin isn't still in scope but I'm not receiving any errors that would indicate that.


repadmin and regex for powershell

$
0
0

Hi,

I need some help to find good regex to create custom powershell object from repadmin.

I use repadmin /showrepl and repadmin /replsum

I share here sample of both repadmin command in french and in xlsx what I want to obtain with regex

https://1drv.ms/u/s!AtpILVXbXteGh1FSbRysh7IeGn7n

Thanks for your help



Merci de marquer comme reponses les interventions qui vous ont ete utile.

Write Output of a function in powershell window

$
0
0

I have a GUI and it calls a function depending on the button pressed. I would like for the output of the function to show in the powershell command window when I run the GUI. The code below contains 5 buttons, when I run the powershell script and click on any of the 5 buttons, nothing happens and it just hangs, until i close out of it.

# This is code for the GUI ▼
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()

$Form                            = New-Object system.Windows.Forms.Form
$Form.ClientSize                 = '406,414'
$Form.text                       = "Post DC Patching Checker"
$Form.TopMost                    = $false

$Check_NetLogon                  = New-Object system.Windows.Forms.Button
$Check_NetLogon.text             = "Check Netlogon"
$Check_NetLogon.width            = 340
$Check_NetLogon.height           = 50
$Check_NetLogon.location         = New-Object System.Drawing.Point(15,17)
$Check_NetLogon.Font             = 'Microsoft Sans Serif,10'

$Ping                            = New-Object system.Windows.Forms.Button
$Ping.text                       = "Ping Servers / Workstations"
$Ping.width                      = 340
$Ping.height                     = 50
$Ping.location                   = New-Object System.Drawing.Point(16,97)
$Ping.Font                       = 'Microsoft Sans Serif,10'

$ShowReplication                 = New-Object system.Windows.Forms.Button
$ShowReplication.text            = "Show Replication"
$ShowReplication.width           = 340
$ShowReplication.height          = 50
$ShowReplication.location        = New-Object System.Drawing.Point(16,183)
$ShowReplication.Font            = 'Microsoft Sans Serif,10'

$DiskSpace                       = New-Object system.Windows.Forms.Button
$DiskSpace.text                  = "Disk Space"
$DiskSpace.width                 = 340
$DiskSpace.height                = 50
$DiskSpace.location              = New-Object System.Drawing.Point(15,267)
$DiskSpace.Font                  = 'Microsoft Sans Serif,10'

$CheckDNSsuffix                  = New-Object system.Windows.Forms.Button
$CheckDNSsuffix.text             = "Check IP Configuration"
$CheckDNSsuffix.width            = 340
$CheckDNSsuffix.height           = 50
$CheckDNSsuffix.location         = New-Object System.Drawing.Point(17,350)
$CheckDNSsuffix.Font             = 'Microsoft Sans Serif,10'

$Form.controls.AddRange(@($Check_NetLogon,$Ping,$ShowReplication,$DiskSpace,$CheckDNSsuffix))

$Check_NetLogon.Add_Click({ CheckNetLogon })
$Ping.Add_Click({ PingServersAndWorkstations })
$ShowReplication.Add_Click({ ShowReplicationOnServers })
$DiskSpace.Add_Click({ ShowDiskSpace })
$CheckDNSsuffix.Add_Click({ ShowIPconfig })
# This is code for the GUI ▲


# Check the netlogon service ▼
function CheckNetLogon { 
    $netLogon =Get-Service -DisplayName netlogon 
        if ($netLogon.Status -eq "Running"){
        $netLogon.DisplayName + 'Service is running already'}
    }
# Check the netlogon service ▲


# Ping's several workstations and servers ▼
function PingServersAndWorkstations {
        ping Test1
        ping Test2

    }
# Ping's several workstations and servers ▲


# Shows replication ▼
function ShowReplicationOnServers {
        repadmin /showrepl
    } 
# Shows replication ▲


# Shows disk space ▼
function ShowDiskSpace {
        Get-WmiObject -Class Win32_logicaldisk  | 
        Select-Object -Property DeviceID, DriveType, VolumeName, 
        @{L='FreeSpaceGB';E={"{0:N2}" -f ($_.FreeSpace /1GB)}}
    }
# Shows replication ▲



# Shows IP config ▼
function ShowIPconfig {
        ipconfig
   }
# Shows IP config ▲

Write-Output $ping

[void]$Form.ShowDialog()

what exactly is the null part in this error?

$
0
0

I have 2 scripts

script1 has the following:

Function Query($Query) {
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection 
$SqlConnection.ConnectionString = "Server=$DB_Server;Initial Catalog=$Database;Integrated Security=SSPI" 
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand 
$SqlCmd.Connection = $SqlConnection 
$SqlCmd.CommandText = $Query 
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter 
$SqlAdapter.SelectCommand = $SqlCmd 
$DataSet = New-Object System.Data.DataSet 
$a=$SqlAdapter.Fill($DataSet)
$SqlConnection.Close() 
$DataSet.Tables[0] }

#create .net array object for csv export
$exportObject = New-Object System.Collections.ArrayList
#create ordered dictionary so column names come out in the ordered they were created
$rowObject = [ordered]@{}

$connection_string = "Connection Timeout=120;User Id=UID1;Data Source=datasource.com;Password=password12!553"

$rowObject.'Connection Details' = $connection_string

#INSERT connection string into Table

Query "UPDATE [$someTable]
SET [connection_string] = '$connection_string'
WHERE [cname] = '$cinput' AND ([pserver] = '$pinput'"

$exportObject.Add((New-Object PSObject -Property $rowObject)) | Out-Null

$exportObject | Select-Object

Now in script2, i call script1 and out-variable the object then convert it to a pscustomobject to use it with an HTML Table function (not relevant to this thread so wont include in code. more info on that here)

script2:

& ".\script1.ps1" -ViewConnection "$cinput" -OutVariable xprtOut | Format-Table -Wrap

#converting xprtOut from Arraylist to pscustomobject to be used with ConvertTo-HTMLTable 
$Arr = @()
Foreach ($Object in $xprtOut) 
{
    $i=-1
    $arrayListCount = -($Object | gm | Where-Object {$_.MemberType -like "noteproperty"}).count

    $customObj = New-Object pscustomobject
    do {
        $customObj | Add-Member -MemberType NoteProperty -Name (($Object | gm)[$($i)].Name) -Value ($Object."$(($Object | gm)[$($i)].Name)")
        $i--
    } while($i -ge $arrayListCount)

    $Arr += $customObj
} 

when i run script2, i get the following errors:

gm : You must specify an object for the Get-Member cmdlet.

$arrayListCount = -($Object | gm | Where-Object {$_.MemberType -l ...

Cannot index into a null array.

... dd-Member -MemberType NoteProperty -Name (($Object | gm)[$($i)].Name) ...

After some long debugging, i found the root problem: by removing the Update Query statement from script1, script2 stopped erroring and it started working just fine.

so the question is, why would the Query statement in script1 be problematic? what does it have to do with the object conversion??

SCCM Application to Change Command Line

$
0
0

Hello, I am writing a PowerShell script to change the Installation Program command line of certain applications in the ConfigManager. Hypothetically, I want to replace only a certain part of the command line with a full path to the application.I used the -ApplicationName and -DeploymentTypeName as an example.Every time I run the program, I get prompted for the MobileMsiInstaller, but whatever I put down just gives me an error that I put a 'System.String' type where it should be a 'System.Management.Automation.SwitchParameter'. I've ran it with the parameter included as if it is a SwitchParameter, but then it just tells me "No object corresponds to the specified parameters." 

 Set-CMDeploymentType -ApplicationName "AdmPwd" -DeploymentTypeName "AdmPwd" -InstallationCommandLine "C:\Windows\System32\WindowsPowerShell\v1.0\Powershell.exe -executionpolicy bypass -file install.ps1" -Language "en-US" -WhatIf

Any help would be appreciated, thanks!

Getting SQL version info from list of server names

$
0
0

I am wondering if there is a powershell script I can run against a .txt file with server names in it that will return the version of SQL on that list of servers. Any help is appreciated.

Thanks.


Chad Guiney

Viewing all 21975 articles
Browse latest View live


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