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

Updating the active directory group membership using the instance of PowerShell.

$
0
0

I am building an application that interacts with Active Directory using System.Management.Automation (Not using Directory Services because currently new to that library and learning it). To update the group membership of for a group in the active directory I am creating a JSON object on my view and invoking a function to pass the object & the URI from front end to back end via a function in my controller.

The basic idea is to allow removal of AD group members in bulk by passing the JSON object as a parameter to the shell script which will be executed in an instance of PowerShell created in the function. I am using .ajax call to invoke the controller function and passing the JSON object that I generated as an argument along with the current URI. The shell.commands.AddParameter() function accepts argument in only string format. So, I typecasted it with ToString() and converting it to JSON in the PowerShell script. I am passing the URL from code behind as the URL is subject to change. I am not getting any errors However, I am also not able to see any update in membership in the AD. Json Object is getting generated from HTML Table.

My shell script

param($objMemberUpdate, $uri)
$body = $objMemberUpdate | ConvertTo-JSON
Invoke-WebRequest -Uri $uri -Method Post -Body $objMemberUpdate

My Controller Function in ASP MVC to Invoke PowerShell Instance and executing Shell Script file from specified location.

private string UpdateMemberList(JsonResult objMemberUpdate)
    {
        var uri = HttpContext.Request.Url.AbsoluteUri;
        var shell = PowerShell.Create();
        shell.Commands.AddCommand(AppDomain.CurrentDomain.BaseDirectory + "Shell\\Set-ADGroupMembership.ps1").AddParameter(objMemberUpdate.ToString(), uri);
        var results = shell.Invoke();
        shell.Dispose();
        return results.ToString();
    }

The Ajax Call that I am calling on a button click on my HTML page.

//Make Array Object to pass in the API For Membership Update
    $("#btnUpdate").click(function () {
        var RemoveMembers = [];
        var RemoveAfter = [];
        var MemberUpdate = {};
        var GroupGUID = "";
        $("table [id*=ddlReqdAdjustment]").each(function () {
            if ($(this).val() != "Keep") {
                GroupGUID = $(this).parent().parent().children().eq(4)[0].innerText;
                var date = $(this).parent().parent().children().eq(8)[0].firstElementChild.value;
                var ObjectGUID = $(this).parent().parent().children().eq(3)[0].innerText + "@@" + $('#ddlDirectory').val();

                if ($(this).val() == "Remove") {
                    var format = ObjectGUID;
                    RemoveMembers.push(format);
                } else {
                    var format = date + "|" + ObjectGUID;
                    RemoveAfter.push(format);
                }
            }
        });
        MemberUpdate = {"Directory": $('#ddlDirectory').val(),"Group": GroupGUID,"Remove": RemoveMembers,"RemoveAfter": RemoveAfter,"ResultFormat": "json","OnBehalfOf": "11112201"            
        };
        console.log(MemberUpdate);
        $.ajax({
            type: "POST",
            url: "/Group/UpdateMemberList",
            data: { objMemberUpdate: MemberUpdate },
            success: function (response) {
                alert(response.message);
            }
        });

The selected member in the table is supposed to get removed from the Group whose GroupGUID (ObjectGUID attribute in AD) is mentioned from the AD. However, no compile time or no runtime error is encountered and nit even any changes are reflected and I think this must be due to problem with my JSON Object?



Powershell to copy remote server files to local logged in user

$
0
0

Hello everyone, i tried scouring the technet forums, but couldnt find anything in this situation.

Example, im getting a new machine, I have 3 co-workers total.

What id like to do is:

co-worker 1 logs in and my new machine script fires off and copies the companies files 

co-worker 2 logs in and my new machine script fires off and copies the companies files 

Currently what happens is i have a set location for the files, but id like to make it a variable. 

I found this article:  it mentioned a command but powershell is giving me an error with the :

$ShortcutFile = "$env:%userprofile%\Desktop"

File and folder permissions, correct and synchronize acl

$
0
0

We have a (large) file and folder structure where something /someone altered vast amounts of file and folder permissions.

Now we have access to and restored a previous state of said structure to a different location and the permission structure is consistent with the required configuration and setup.

I tried to combine get-childitem, get-acl and set-acl but I am constantly running into a brick wall - most likely related to (lack of) experience regarding this matter.

And now I am wondering if and hoping that one of you absolute geniuses is able to provide me with pointers and/or a rudimentary setup that I may use for this exercise.

Look forward to reading your feedback
Cheers, Andor

How to call sconfig utility from powershell script and passing input

$
0
0
Hi

I want to call sconfig utility from powershell script and passing input. Can somebody please advise how to do it?

For instance I want to run sconfig and choose 5 option. Then I want to choose M. How would you do it in powershell ps1 script?

Thanks

Altaf



How to run several batch files in parallel and wait for them all to complete before continuing - with arguments

$
0
0

i have a bunch of processes i would like to run in parallel using powershell.  

I found a bunch of examples where i can do this

$scripts = 'c:\j1.bat', 'c:\j2.bat','c:\j3.bat'

$scripts |%{ Start-Job –scriptblock (iex "[Scriptblock] { & '$_' }") } | wait-job

However, i would like to send arguments to the same batch file.

e.g.

$scripts = 'c:\j.bat 1', 'c:\j.bat 2','c:\j.bat 3'


$scripts |%{ Start-Job –scriptblock (iex "[Scriptblock] { & '$_' }") } | wait-job

Is there an argument to pass an argument?  When i run above it fails.

Thanks in Advance!

script to overwrite a file

$
0
0

Hi,

We have a client which has this application. The vendor of the app advised us to change a particular xml file in all computers. I was thinking of using a software deployment to run a powershell script to overwrite the existing filename

Thanks

Jeff

Feeding text file to Powershell Scritp

$
0
0

I am trying to run a powershell script I found that, running by itself gets all computers in the domain. However I have a .txt file that has specific computer accounts that I want to feed to the script so it only runs against those accounts. below is the script command....

Get-ADComputer -Filter * -Properties * | select samaccountname,canonicalname,operatingSystem,lastLogonTimestamp

I want to be able to have it reference a computers.txt so the above command only runs against those names. Any help is much appreciated.

THanks.


Chad Guiney

PS AD Module: "error initializing default drive"

$
0
0

The exact error is listed below. Everything I have read points to ADWS, but the eventlogs for ADWS look good. Thus far we have tried bouncing the service, and then the box, both to no avail. This box is not a DC however it does have ADAM installed for LDS.

WARNING: Error initializing default drive: 'Unable to contact the server. This
may be because this server does not exist, it is currently down, or it does not
 have the Active Directory Web Services running.'.    

Script to remove System Center Agent

$
0
0

I have this script to remove the system center agent, but the Next options pop up as if I am manually removing the agent by choosing Change instead of Uninstall. I tried using the quiet option but that did not work.  How can I write the script so that it actually uninstalls with no popups as if I am changing the agent?

$SysCtr2007=Get-ChildItem-PathHKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall|`   

Get-ItemProperty| Where{$_.DisplayName-match"System Center Operations Manager 2007 R2 Agent"}

ForEach

( $verin$SysCtr2007) {  

If($ver.UninstallString ) {     

$uninst=$ver.UninstallString       

Start-Processcmd-ArgumentList"/c$uninst/quiet /qn "


    }

}

Account Expiration email notification

$
0
0

I've parsed together a few scripts found here to create a script that will:

- Notify a users manager if the users account will expire within 30 days. 
- If the user does not have a listed manager, default to the helpdesk

My issue is (besides I'm not a powershell expert) is that a manager who has multiple employees with expiring accounts will receive multiple emails (i.e. We have some managers receiving 20-30 individual emails for individual users). Is there a way to change this so that each manager will only receive one email with a list of users?

Based on how this is written, I'm not sure how to parse it all into an array (or another solution?) being it is processing it one-by-one currently? Any help/thoughts or editing would be extremely appreciated!!

------                    

Function Get-UsersEmail{
   [CmdletBinding()]
   Param(
      [Parameter(Position=0,
         Mandatory=$True,
         ValueFromPipeLine=$True,
         ValueFromPipeLineByPropertyName=$True)]
      [String]$adsPath
   )
   Try{
      $user  = [ADSI]"LDAP://$adsPath"
      $email = $user.mail
   }Catch{
      [String]$email = ""
   }
   Return $email
}

# Determine expiration date and return "<never>" or expiration date in variable $expiry
Function Get-ADUserExpiry{
   [CmdletBinding()]
   Param(
      [Parameter(Position=0,
         Mandatory=$True,
         ValueFromPipeLine=$True,
         ValueFromPipeLineByPropertyName=$True)]
      [String]$sid
   )
   $user           = [ADSI]"LDAP://<SID=$sid>"
   $accountExpires = $user.accountExpires.Value
   $longValue      = $user.ConvertLargeIntegerToInt64($accountExpires)
   If($longValue -gt [DateTime]::MaxValue.Ticks){
      $longValue = 0
   }
   $dateValue = [DateTime]$longValue
   If($dateValue -eq 0){
      $expiry = "<Never>"
   }Else{
      $expiry = [DateTime]::FromFileTime($user.ConvertLargeIntegerToInt64($user.accountExpires.Value))
   }
   Return $expiry
}

# End of functions
# ----------------------------------------------

# Define Variables
$default  = "helpdesk@company.com"
$LineBreak   = "`r`n"

Import-Module ActiveDirectory
$results = search-adaccount -AccountExpiring -TimeSpan "30" -usersonly

ForEach($result In $results){
   Do{
      # Set variable to string
 $expiry    = ""
      $to        = ""
      $body      = ""

 #
 $subject   = "User Account Expirations"
      $sid       = $result.SID
      $userName  = $result.sAMAccountName

      #get distinguished name/sid of user
 $user      = [ADSI]"LDAP://<SID=$sid>"
      $manager   = $user.Manager
      $firstName = $user.givenName
      $lastName  = $user.sn

 # Passes $SID to above function 'get-aduserexpiry' and saves the expiration date to $expiry
      $expiry    = Get-ADUserExpiry $sid

 # If manager exists, call function get-usersmail on the manager
 If($manager -ne ""){
         $to = Get-UsersEmail $manager
      }

 # If no manager exists set to field as default (helpdesk)
 Else{
         $to = $default
      }

 # Send email if Manager exists and Expiration exists
      If($to -ne "" -And $expiry -ne "<Never>"){
         $subject += " - $firstName $lastName"
         $body    = "You are listed as the manager responsible for the following user account which will expire in 30 days. Please email the helpdesk if the account should remain enabled." + $LineBreak + $LineBreak
         $body    += "LogonName: $userName"  + $LineBreak 
         $body    += "FirstName: $firstName" + $LineBreak
         $body    += "LastName: $lastName"   + $LineBreak
$body    += "Listed Manager: $to"   + $LineBreak
         $body    += "ExpiryDate: $expiry"   + $LineBreak + $LineBreak 
$body    += "Thank You"+ $LineBreak
                
         Write-Host "Sending email to users manager ($to) for user $userName"
         Write-Host $subject
         Write-Host $body
         Write-Host ""
         Send-MailMessage -To $to -From "helpdesk@company" -Subject $subject -Body $body -smtpserver "xxx"
}
   }Until($True)
}

----

more-info: What I'm asking is very similar to this user (http://stackoverflow.com/questions/16533334/powershell-script-for-soon-to-expire-ad-users), but it isn't quite working properly (i.e. the display looks poor and lists all information duplicated in the email instead of just the user name) and that requires an imported .csv of all users and their managers which I don't have and haven't determine how to create.

The workflow definition has been recycled, because the workflow definition cache limit of 1000 has been reached

$
0
0

Hi all,

We are experiencing a issue executing a long powershell processes. We get this message:

The workflow definition has been recycled, because the workflow definition cache limit of 1000 has beenreached

This occurs after October 2018 patch in Windows 2016 Datacenter Server edition. For a while was possible uninstall this patch but now, after December update, isn't possible do this.

There is a workaround but don't work.

Are there any related issue?

Regards,

Eduard.


escaping single quotes inside a variable

$
0
0

I am currently using scom to execute a powershell command which passes the scom alert description into the script. the alert description variable in scom has to be surrounded by single quotes to pass over however the containing string also contains single quotes so is being cut short. 

anyone have any suggestions on how I can get powershell to ignore the single quotes inside the string ?

command being used is                        "C:\SCOM\Scripts\syslogcreateevent.ps1" '$Data/Context/DataItem/AlertDescription$'

with the string variable being                Alarm event description: testing single ' quotes'


Richard Scott


No such interface supported

$
0
0

Hi All,

When I am running a below powershell command I am getting an error message as "No such interface supported";

gwmi win32_operatingsystem -ComputerName "hostname"

I am able to access target host through RDC from the source host. I can telnet the host and its listening on 135. All windows firewalls are disabled. Trying with Admin account. 

Any idea how to get rid of this error?

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 get all groups and members of a nested group into csv format with Export-Csv

$
0
0

Hello

I am new to Powershell scripting so i need a little help :)

I have a AD Group which have many nested groups with members in each group

I want to get a csv file with name of the nested group inside a group and the name of the member in the nested groups with their emai address

I have tried with PS script under but i am not able to get file formated correctly with one colum for group name and one for name and one for email so i can import it into Excel

get-ADGroupMember "ADgroup" | ?{$_.ObjectClass -eq "Group"} | %{Write-output $_.Name;Get-ADGroupMember $_ | Select-Object Name} |format-list | Out-File c\temp\groups.csv

If anyone could help me i would appreciate it.

Morten


mh


download windows patch files(patchid like KBxxxxx) and save it into local disk using powerShell

$
0
0

Dear Team,

Greetings !

I am very new to PowerShell i would to make script to download patch files using Patch ID (KBxxxxx) and save it local disk to install whenever its required.

i am using powershell version 2.0

Request you to kindly help me.

Thanking in advance.

bulk export members and update dynamic distribution group

$
0
0

Hello, 

How do I export group members in an O365 dynamic distribution group to a CSV file?

What is the Azure power shell command to read a CSV file with list of UPNs and populate names into an O365 dynamic distribution group?

Please advise.  

Thanks. 

Trouble Splitting String?

$
0
0

Greetings, 

I have a file with: 

Y21 M3_SWO JTAG_TDO/M3_TDO/M3_SWO Reserved 
Y22 M3_TRSTB JTAG_TRSTB/M3_TRSTB Reserved 

I have the following code to read  the file then try to process 
each element on the line: 

$a = Get-Content -Path .\pin.txt 

foreach ($line in $a) { 
        #$element = $line.Split(" ") 
        $element = $line -split "\s+" 
        Write-Host "E1: $element[0]" 


However the .Split or -split doesn't work? I get: 

E1: Y21 M3_SWO JTAG_TDO/M3_TDO/M3_SWO Reserved[0] 
E1: Y22 M3_TRSTB JTAG_TRSTB/M3_TRSTB Reserved[0] 

I've tied to convert to a string or  pipe to Out-String on the reading, but 
that didn't work. I also checked to see if it thinks there's a space in the line with -contain, Powershell doesn't see this as a string? Any idea what I'm doing wrong? Why is it not spliting the line variable into an array? 


Thanks in advance for any help! 
  Zihav

to list the AD users and associated/member group

$
0
0

Hi Techies,

i need to pull a report using powershell script for all the admin users in AD and the associated groups with respect to each users.

I tried to run the below script but i am not getting the desired output. can anybody please assist. 

Get-ADUser -Filter 'SamAccountName -like "admin.*"' -Properties * | Select ’DisplayName’,’SamAccountName’, @{Name=’MemberOf’; Expression={$_.MemberOf -join “;”}}|ft -autosize

regards

VKS


Query remote servers Windows Services Logon As information.

$
0
0
We want to decommission a domain service account. We want to make sure there is no window service on the domain member servers running using that service account.  

May someone advice some PS commands to remotely query Windows services and LOGON AS information?  

I have tried the below but it does not work.  Please advise.  Thanks.

$server = Get-Content -path C:\Servers.txt
$server | foreach { (Get-Service -computername $_) |Select-Object Status, Name, DisplayName, MachineName, logonas } | Export-csv -Path C:\Services on remote servers.csv
Viewing all 21975 articles
Browse latest View live


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