Quantcast
Channel: PowerShell General
Viewing all 10624 articles
Browse latest View live

Access denied when remotely running a batch file

$
0
0

Hello everyone,

I need to remotely run a batch file, same way as the author of this topic needed to: http://powershell.com/cs/forums/t/14235.aspx?PageIndex=3

My batch file needs to open the user's browser and perform a few actions, just as an user would do, like access google and perform a search, for example. It is an automated script triggered by a batch file, but I need to SEE it running.

Here is what I have so far:
- I have two computers (let me call them as comp1 and comp2) with psremoting enabled in both of them so they can "see" each other.
- I'm currently in comp1 and trying to run the following code:
Invoke-Command -Computer comp2 -Credentials domain\user -ScriptBlock { Start-Process "\\comp2\share\echo.bat"

But I'm getting the following error message:
This command cannot be executed due to the error: Access is denied
CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
FullyQualifiedErrorId : InvalidOperationException,Microsoft.ProwerShell.Commands.StartProcessCommand

Both comp1 and comp2 are Administrators, and the file is in a shared folder. So what am I missing?

Additional info:
echo.bat is just echoing a "Hello World" and saving it in a txt file.
Reminding that this file is currently located in comp2, but I need to run it from comp1


I also tried the following:
wmic /NODE:comp2 process call create "C:\shared_folder_path\excho.bat"

This actually worked, but I couldn't see the actions being performed in comp2 screen.
Is there any way to get this done?

Sorry about the long (and kinda messy) post. I'd really appreciate any help
Thank you very much in advance


[Help] Format the result of an excel file

$
0
0

How can i transform the result in an excel format. In that there is a result but it is in .txt file

Please see attached file it is zipped the code is long (Please visit the site to view this media)

Like for the first result instead of:
1. GRANT SELECT statement found in DBSCRIPTS\DB_FUNCTIONS\FN_RESOURCE_SLHLALL_GET_DYN_COLUMNSNJOINS.sql Line >> -- GRANT SELECT ON DBO.FN_RESOURCE_SLHLALL_GET_DYN_COLUMNSNJOINS TO Abacusi, Admin_ai (result is on 1 row)

I want to get the below result like this:
1. GRANT SELECT statement found in DBSCRIPTS\DB_FUNCTIONS\FN_RESOURCE_SLHLALL_GET_DYN_COLUMNSNJOINS.sql Line
 >> -- GRANT SELECT ON DBO.FN_RESOURCE_SLHLALL_GET_DYN_COLUMNSNJOINS TO Abacusi, Admin_ai (result is on 2 separate rows)

PS Object Behaivour

$
0
0

I am new to powershell

Using  a power shell script to deploy my SSRS reports

I have run into weird problem 

extracts from script 

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

Create Data source function

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

function New-SSRSDataSource ($Proxy,[string]$RdsPath,[string]$Folder,[switch]$Overwrite) {

    Write-Verbose "New-SSRSDataSource -RdsPath $RdsPath -Folder $Folder"

 

    $Folder = Normalize-SSRSFolder -Folder $Folder

 

    [xml]$Rds = Get-Content -Path $RdsPath

    $ConnProps = $Rds.RptDataSource.ConnectionProperties

 

    $Definition = New-Object -TypeName SSRS.ReportingService2010.DataSourceDefinition

    $Definition.ConnectString = $ConnProps.ConnectString

    $Definition.Extension = $ConnProps.Extension 

    if ([Convert]::ToBoolean($ConnProps.IntegratedSecurity)) {

        $Definition.CredentialRetrieval = 'Integrated'

    }

        $hash =@{

        Name = $Rds.RptDataSource.Name

        Path =  $Folder + '/' + $Rds.RptDataSource.Name

    }

    $DataSource = New-Object -TypeName PSCustomObject -Property $hash

 

    if ( $Overwrite -or  $Proxy.GetItemType($DataSource.Path) -eq 'Unknown') {

 

        $Proxy.CreateDataSource($DataSource.Name, $Folder, $Overwrite, $Definition, $null)

    }

 

    return $DataSource

}

 

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

where Its referenced

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

$DataSourcePaths = @{}

$Project.SelectNodes('Project/DataSources/ProjectItem') |

    ForEach-Object {

   $RdsPath = $ProjectRoot | Join-Path -ChildPath $_.FullPath

        "$RdsPath"

$DataSource = New-SSRSDataSource -Proxy $Proxy -RdsPath $RdsPath -Folder $DataSourceFolder 

 

$DataSource|Out-GridView

 

       $DataSourcePaths.Add($DataSource.Name,$DataSource.Path)

    }

I have two Items in 'ProjectItem' node so essentially for loop should  execute for two times

current behaivour

   when I execute script for the first time

following are results from both grid view and error message at powershell prompt

Grid View

0SSRS.ReportingService2010.CatalogItemSSRS.ReportingService2010.CatalogItem

1@{Name=Verification Relational DS; Path=/Data Sources/Verification Relational DS}System.Management.Automation.PSCustomObject

Prompt
ForEach-Object : Property 'Name' cannot be found on this object. Make sure that it exists.
At C:\Users\prabhakar.munugala\Documents\Visual Studio 2010\Projects\DVSDashBoard\DVSDashBoard\Deploy-SSRS
68 char:19
+     ForEach-Object <<<<  {
    + CategoryInfo          : InvalidOperation: (.:OperatorToken) [ForEach-Object], RuntimeException
    + FullyQualifiedErrorId : PropertyNotFoundStrict,Microsoft.PowerShell.Commands.ForEachObjectCommand
When I execute it second time
it would have two grid views as '$DataSourcePaths.Add($DataSourcePaths.Add($DataSource.Name,$DataSource.Path)'
has got 'Name' and 'Path' properties
But it fails on the second data source
below are results
GridView1

Verification Relational DS/Data Sources/Verification Relational DS

GridView2
0SSRS.ReportingService2010.CatalogItemSSRS.ReportingService2010.CatalogItem
1@{Name=VerificationCube; Path=/Data Sources/VerificationCube}System.Management.Automation.PSCustomObject
Prompt
ForEach-Object : Property 'Name' cannot be found on this object. Make sure that it exists.
At C:\Users\prabhakar.munugala\Documents\Visual Studio 2010\Projects\DVSDashBoard\DVSDashBoard\Deploy-S
68 char:19
+     ForEach-Object <<<<  {
    + CategoryInfo          : InvalidOperation: (.:OperatorToken) [ForEach-Object], RuntimeException
    + FullyQualifiedErrorId : PropertyNotFoundStrict,Microsoft.PowerShell.Commands.ForEachObjectCommand
When I run for the third time 
every thing is good
Below are results
GridView1
VerificationCube/Data Sources/VerificationCube
GridView2
Verification Relational DS/Data Sources/Verification Relational DS
and Script executes well
Issue :- Returned PSObject , on initial run is not returning the expected value
any help would be appreciated

Software triggered IRQ in PS

$
0
0

Hi,

 

Is there  a way in powershell to initiate software triggered IRQ. I am trying to use the Measure-command to find the execution time of a script block. But due to the high CPU queue length, I see delays in milliseconds. Since the expected result is within milliseconds, even a slight delay in seconds makes much difference in the final result.

 

Regards

 

Ranjith A Paul

Powershell script run by end users

$
0
0

Hi,

I am hoping someone can point me in the right direction.  I have a requirement for end users to be able to run a powershell script to reset a leader PIN for a conferencing service hosted on Lync.  I imagined being able to host a webpage on our intranet that will get the details of the currently logged on user, run the powershell command to reset their PIN and drop the user an email.  I could also provide this script to the helpdesk with a manual user input field to allow them to easily reset leader pins without using the admin UI.

I am OK with writing a script to get the current user, and send the email it's the webpage part that I am struggling with, and the remote session to the Lync servers to run the script.   I know there is a UI to do this in Lync but most of our users are not EV enabled so it won't work for them.  The idea here being that the user never knows it's a script running in the background it is just a webpage they visit, press a button and a few mins later they get an email with their new PIN.

One idea that has just come to me, is it may be easier to have the script running as scheduled job on the server and the webpage just creates a temp file on the server with the details of the request in.  Then every 5 mins the job picks that up and resets the pins in a batch.

Any suggestions would be helpful, if it's a silly idea tell me!

Thanks

A way to copy only diffs from a file

$
0
0

Hello, i am trying to find a way to copy only a difference from a log file.

I have .txt files in  following format:
20140413 133812-log events AAAA......
20140413 133812-log events BBBB!
20140319 130545-log events CCCC!

I want to run the script and if there is a new lines which are logged after the last time i have checked the file i want to copy only them.

I am not sure how to proceed, should i try to count rows in the file, store the number in some file and then copy everything after that, and after that write the new rows number .. and so on.

I don't think this is a good approach ..
or somehow should i try to get the new lines by date and time..

Can someone give me an advice..

 

Formatting Heck

$
0
0

I have this code and it works.

 

foreach ($Machine in Get-Content "c:\temp\tmp\Machines.txt") {Get-WMIObject win32_mappedlogicaldisk -ComputerName $Machine  | Select Name, ProviderName | fl} 

 

This will read the .txt file and then return all mapped drives for the "User" on the remote machine (very slick!).  

the output looks like this.

 

Name         : P:

ProviderName : \\mgmgs4ms\Medstreaming$

 

Name         : R:

ProviderName : \\MGMGS4MS\MGMainshare

 

 

I need to include the Machine Name for each machine.   I will run this against 50 machines or more and I'm not sure how to 1) add the machine name and 2) the proper way to format this.

 

Cannot add a new UPN-Suffix in a trusted domain/Forest with powershell

$
0
0

Hi everyone

I´m trying to add a new UPN suffix, in a different forest/domain than my multi tenant Exchange 2013 domain. There is a transitive trust between the two domains/forests.

 

Import-Module activedirectory

New-PSDrive–Name Domain –PSProvider ActiveDirectory –Server ‘DC01.domain.local’ –credential (Get-Credential‘domain.local\administrator’) –root‘//RootDSE/’

 

$CustomerName = Read-Host"Add new UPN Suffix)"

Set-ADForest-Identity domain.local -UPNSuffixes @{Add="$CustomerName"}

A “Get-ADForest -Identity domain.local –Server ‘DC01.domain.local’| fl” works fine, but when I run the above powershell commands, I get this error:

 

****************************************************************

Name           Used (GB)     Free (GB) Provider      Root                                                CurrentLocation

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

Domain                                 ActiveDire... //RootDSE/                                                        

 

Set-ADForest : A referral was returned from the server

At line:12 char:1

+ Set-ADForest -Identity domain.local -UPNSuffixes @{Add="$CustomerName"}

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : ResourceUnavailable: (domain.local:ADForest) [Set-ADForest], ADReferralException

    + FullyQualifiedErrorId : ActiveDirectoryServer:8235,Microsoft.ActiveDirectory.Management.Commands.SetADForest

****************************************************************

 

Can anyone help

Best Regards

Peter
A-One Solutions


FInd users where initials is empty

$
0
0

HI

I would like to extract all users thaht don't have anything in the field intials

?

 

Get-ADUser -Filter * | where { $_.initials -eq " " } | Select-Object -Property SamAccountName,surnameu

 

Thank you

Export to CSV into seperate columns

$
0
0

Hey Guys :)

I have a script from one of the guys at work that I'm trying to modify, sorry but I'm still a total noob and still haven't had time to do basic powershell training, just flat out doing donkey work.

I think this script does other stuff that I'm not familiar with but all I want to do is have the output CSV file put the data in seperate columns as opposed to having it all in the first column.

I looked at Export-CSV and Set-Content etc but couldn't work out how to add Export-CSV to the script. I had a play with Export-CSV and it worked for command line stuff but again, no idea how to get the CSV formatting correct.

$Computers = Get-Content "C:\Data\SnagIT\Snagit Computers-LastLoggedInUsers.txt" is just a list of Computer names.

Ive just changed the txt below to csv:

$LogonFile = "C:\Data\SnagIT\LastLogon_" + $DateTimeStart + ".csv"

 

any help would be much appreciated and thank you kindly :-D

 

 

<# Filename: Get-LastLogonAndComputers.ps1 
Written by:  Sam Eng
Date: 2013-09-05
This script produces 3 outputs: ActiveComputers.txt, LastLogon_2013
This script extracts a list of all active computers from AD, extracts the last logged on
information from each computer and writes the info to a file.
Where a computer is unavailable, only the computer name is shown.
#>

Import-Module ActiveDirectory

# get today's date
$today = Get-Date

#Get today - 60 days (2 month old)
$cutoffdate = $today.AddDays(-60)
$outputfile = "C:\Data\Snagit Computers-LastLoggedInUsers.txt"
#Clear-content $outputfile;
#Get-ADComputer  -Properties * -Filter {LastLogonDate -gt $cutoffdate} |`
#Select-Object -Property Name | Sort-Object -Property Name| `
#ForEach-Object {Add-Content $outputfile $_.name}

#--------------------------------------------------------------------------

Function Get-LastLogon
{
[CmdletBinding()]
param(
  [Parameter(Position=0,ValueFromPipeline=$true)]
  [Alias("CN","Computer")]
  [String[]]$ComputerName="$env:COMPUTERNAME",
  [String]$FilterSID,
  [String]$WQLFilter="NOT SID = 'S-1-5-18' AND NOT SID = 'S-1-5-19' AND NOT SID = 'S-1-5-20'"
  )
 
Begin
  {
    #Adjusting ErrorActionPreference to stop on all errors
    $TempErrAct = $ErrorActionPreference
    $ErrorActionPreference = "Stop"
    #Exclude Local System, Local Service & Network Service
  }#End Begin Script Block
 
Process
  {
    Foreach ($Computer in $ComputerName)
      {
        $Computer = $Computer.ToUpper().Trim()
        Try
          {
            #Querying Windows version to determine how to proceed.
            $Win32OS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $Computer
            $Build = $Win32OS.BuildNumber
            
            #Win32_UserProfile exist on Windows Vista and above
            If ($Build -ge 6001)
              {
                If ($FilterSID)
                  {
                    $WQLFilter = $WQLFilter + " AND NOT SID = `'$FilterSID`'"
                  }#End If ($FilterSID)
                $Win32User = Get-WmiObject -Class Win32_UserProfile -Filter $WQLFilter -ComputerName $Computer
                $LastUser = $Win32User | Sort-Object -Property LastUseTime -Descending | Select-Object -First 1
                $Loaded = $LastUser.Loaded
                $Script:Time = ([WMI]'').ConvertToDateTime($LastUser.LastUseTime)
                
                #Convert SID to Account for friendly display
                $Script:UserSID = New-Object System.Security.Principal.SecurityIdentifier($LastUser.SID)
                $User = $Script:UserSID.Translate([System.Security.Principal.NTAccount])
              }#End If ($Build -ge 6001)
              
            If ($Build -le 6000)
              {
                If ($Build -eq 2195)
                  {
                    $SysDrv = $Win32OS.SystemDirectory.ToCharArray()[0] + ":"
                  }#End If ($Build -eq 2195)
                Else
                  {
                    $SysDrv = $Win32OS.SystemDrive
                  }#End Else
                $SysDrv = $SysDrv.Replace(":","$")
                $Script:ProfLoc = "\\$Computer\$SysDrv\Documents and Settings"
                $Profiles = Get-ChildItem -Path $Script:ProfLoc
                $Script:NTUserDatLog = $Profiles | ForEach-Object -Process {$_.GetFiles("ntuser.dat.LOG")}
                
                #Function to grab last profile data, used for allowing -FilterSID to function properly.
                function GetLastProfData ($InstanceNumber)
                  {
                    $Script:LastProf = ($Script:NTUserDatLog | Sort-Object -Property LastWriteTime -Descending)[$InstanceNumber]              
                    $Script:UserName = $Script:LastProf.DirectoryName.Replace("$Script:ProfLoc","").Trim("\").ToUpper()
                    $Script:Time = $Script:LastProf.LastAccessTime
                    
                    #Getting the SID of the user from the file ACE to compare
                    $Script:Sddl = $Script:LastProf.GetAccessControl().Sddl
                    $Script:Sddl = $Script:Sddl.split("(") | Select-String -Pattern "[0-9]\)$" | Select-Object -First 1
                    #Formatting SID, assuming the 6th entry will be the users SID.
                    $Script:Sddl = $Script:Sddl.ToString().Split(";")[5].Trim(")")
                    
                    #Convert Account to SID to detect if profile is loaded via the remote registry
                    $Script:TranSID = New-Object System.Security.Principal.NTAccount($Script:UserName)
                    $Script:UserSID = $Script:TranSID.Translate([System.Security.Principal.SecurityIdentifier])
                  }#End function GetLastProfData
                GetLastProfData -InstanceNumber 0
                
                #If the FilterSID equals the UserSID, rerun GetLastProfData and select the next instance
                If ($Script:UserSID -eq $FilterSID)
                  {
                    GetLastProfData -InstanceNumber 1
                  }#End If ($Script:UserSID -eq $FilterSID)
                
                #If the detected SID via Sddl matches the UserSID, then connect to the registry to detect currently loggedon.
                If ($Script:Sddl -eq $Script:UserSID)
                  {
                    $Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]"Users",$Computer)
                    $Loaded = $Reg.GetSubKeyNames() -contains $Script:UserSID.Value
                    #Convert SID to Account for friendly display
                    $Script:UserSID = New-Object System.Security.Principal.SecurityIdentifier($Script:UserSID)
                    $User = $Script:UserSID.Translate([System.Security.Principal.NTAccount])
                  }#End If ($Script:Sddl -eq $Script:UserSID)
                Else
                  {
                    $User = $Script:UserName
                    $Loaded = "Unknown"
                  }#End Else
 
              }#End If ($Build -le 6000)
            
            #Creating Custom PSObject For Output
            New-Object -TypeName PSObject -Property @{
              Computer=$Computer
              User=$User
              SID=$Script:UserSID
              Time=$Script:Time
              CurrentlyLoggedOn=$Loaded
              } | Select-Object Computer, User, SID, Time, CurrentlyLoggedOn
              
          }#End Try
          
        Catch
          {
            If ($_.Exception.Message -Like "*Some or all identity references could not be translated*")
              {
                Write-Warning "Unable to Translate $Script:UserSID, try filtering the SID `nby using the -FilterSID parameter."  
                Write-Warning "It may be that $Script:UserSID is local to $Computer, Unable to translate remote SID"
              }
            Else
              {
                Write-Warning $_
              }
          }#End Catch
          
      }#End Foreach ($Computer in $ComputerName)
      
  }#End Process
  
End
  {
    #Resetting ErrorActionPref
    $ErrorActionPreference = $TempErrAct
  }#End End
}# End Function Get-LastLogon

Clear
$DateTimeStart =  Get-Date -Format "yyyy-MM-ddThh-mm-ss";
$LogonFile = "C:\Data\SnagIT\LastLogon_" + $DateTimeStart + ".csv"
Write-Host "Start - $DaeTimeStart"
$Computers = Get-Content "C:\Data\SnagIT\Snagit Computers-LastLoggedInUsers.txt";
Set-Content -Path $LogonFile -value "Start Time: $DateTimeStart";
Add-Content $LogonFile "Computer           User                      Time                    CurrentlyLoggedOn"
Add-Content $LogonFile "------------------ ------------------------- ----------------------- -----------------"
#$ErrorActionPreference = "Stop";
foreach($Computer in $Computers)
{
  #$ComputerFile = "C:\Data\SnagIT\" + $Computer + ".txt"
  $output = Get-LastLogon $Computer -ev myError -ea SilentlyContinue
 
 if ($myError -ne $null)
   {
     # We got an error and its stored in $myError.
     Write-Host $Computer ": Failed to access."
     Add-Content $LogonFile $Computer;
   }
 else
   {
     # Everything went as planned, $obj should have the wmi object.
     $pc = $output.Computer
     $user =$output.User
     $time = $output.Time
     $lo = $output.CurrentlyLoggedOn
     $computerstr = "{0,-25} {1,-24} {2,-10}" -f $user, $time, $lo
     $logonstr = "{0,-18} {1,-25} {2,-24} {3,-10}" -f $pc, $user, $time, $lo
     Write-Host $Computer ": " $user
     Add-Content $ComputerFile $computerstr;
     Add-Content $LogonFile $logonstr;
   }
}
$DateTimeEnd = Get-Date -Format "yyyy-MM-ddThh-mm-ss";
Add-Content $LogonFile "  ";
Add-Content $LogonFile "End Time: $DateTimeEnd";
#Write-Host "End - $DateTimeEnd"

 

 

Group Policy Scripting

$
0
0

Hi,

Excuse me for posting a GPO question in AD forum... It would seem the old forum is obsolete?

 

I'm looking to automate GPO Deployement... There are many ways to Rome...

When it comes to Domain Password Policy Set-ADDefaultPasswordPolicy will do the trick.

 

But then it gets tricky...

For Audit Policy you need to create you Security Template using scw. After that you can use scwcmd to transform your template to a GPO... Once you transformed the template, New-GPLink and we're in business...

A detour ... but ok... I can live with that...

 

But...

Advanced Security Audit Policy isn't a subset you can preconfigure... Is that by Design?

My best bet right now to get Advanced Security Audit Policy Settings would be to create a GPO in advanced, Backup & Import...

Is there a cmdlet I missed or a different tool I need to use? Any tips are welcome!!!

 

Regards,

Irwin

Read from CSV and Compare info against AD

$
0
0

Hello,

I have a CSV file that I am treating as Master file. Not all of the headers from the CSV are part of a user in AD.

The master CSV has the following headers:

"Last Name","First Name","Last 4 SSN","Month of Birth","Day of Birth","COMPANY Employee ID","Titles","Department Name","Phone Number"

Need to compare"Company Employee ID" header from the CSV against the employeeNumber of AD User, if they match output the following headers to a new CSV.

Headers from the new CSV: "Last Name","First Name","Last 4 SSN","Month of Birth","Day of Birth","COMPANY Employee ID","Titles","Department Name","Phone Number","Email Address"

But, "Last Name"  and"First Name" comes from AD

"Last 4 SSN","Month of Birth","Day of Birth" comes from the master CSV file

"COMPANY Employee ID","Titles","Department Name", comes from AD,

"COMPANY Employee ID" is employeeNumber in AD. "Titles" is title in AD. "Department Name" is department in AD

"Phone Number" comes from the master CSV file

and"Email Address" comes from AD

if they do not match, the record from the master CSV needs to be part of the new CSV with the same headers mentioned above: "Last Name","First Name","Last 4 SSN","Month of Birth","Day of Birth","COMPANY Employee ID","Titles","Department Name","Phone Number","Email Address"

Thanks for your help, will really appreciate any guidance in the code.

Extract profilepath is empty

$
0
0

Hi,

I am trying to list our AD users along with their profile paths however when I run the command below it lists all the users but the profile paths are all empty even though I know that many users have profile paths set?  I also notice that it only displays the last logon date for a few users.  Am I doing something wrong?

 get-aduser -filter * -properties * | select displayname,office,profilepath,lastlogondate

It is a 2008 AD and I am running powershell on the AD server.

Any advice appreciated.

Thanks

Piping Get-Acl output to icacls.exe

$
0
0

Hello everybody,

my first post here, I'm Luka and I hope to get more proficient with PS.

In a production environemnt, I have a messed up folder with inconsistent permissions. I was hoping to be able to get the files with the required group missing

Get-Acl | where {$_.accesstostring -notlike "*domain\Required_Group*"}

and piping the output to icacls

icacls /grant Required_Group:R

Well, I can't manage. I'm guessing the input format is not correct. I have also tried with the get-acl - set-acl combination but it requires me to change the owner of the files involved.

Any suggestions please?

Thanks, shkdd

 

Powershell CSV report usernames & Phone Numbers - but exclude area code?

$
0
0

Howdy

I am working on a PowerShell report of user names, First, Last, and their phone number populated in AD.

But the request is to take out the area code.  That's not something I've done before, can anyone help me with how to do that?  I'm wondering what happens if the user doesn't have an area code entered in terms of how a script will determine that. 

I think it will be some code to pull of the first 3 digits, but then I'm not sure if I can put something in that would prevent it from ding that if the number is only 7 digits long?


Require a script to find the computer objects in multiple domain

$
0
0

Hi All,

 

I have around 150 Windows servers to which I need to find out if these exists in AD or not.

The problem is I have around 10 domains and I need to find out the servers exist in those 10 domains or not.

Could you please help me with a script to find these objects.

 

Thanks,

S.Mani

Delete disabled AD Accounts that are over 2 years old

$
0
0

Hi

Hoping you can help.

I have been asked to delete all DISABLED AD accounts where the last logon was over 2 years ago. All our disabled accounts are in 1 OU, so I would like to run the powershell script only against that OU. Also, there are acounts in that OU which are disabled and are over 2 years old but the user has never logged in. I would like to delete them as well - if possible. Thank you.

Bulk Set Manager

$
0
0

Hi.

I have this powershell script.

For some reason it will change all other properties but Manager - and I cannot figure out why - any ideas?

My csv contains Manager stated as SamAccountName.

mport-Module Activ*
 $users = $i = $null 
 $users = Get-ADUser -SearchBase "ou=users,dc=domain,dc=com" -filter * -property GivenName,SurName,description,Company,Manager


$Company = “Company”
$GivenName = $user.GivenName
$SurName = $user.SurName
$Description = $user.Description
$Manager = $user.Manager
$office = $User.Office
$Department = $user.Department
$Title = $user.Title

$users = Import-Csv c:\users.csv -Encoding Unicode
$users # dumps users to allow visual inspection
read-host "press Enter to continue or Ctrl+C to abort"
$users | Foreach {Set-ADUser -Identity $_.SamAccountName -Company $Company}
$users | Foreach {Set-ADUser -Identity $_.SamAccountName -GivenName $_.GivenName}
$users | Foreach {Set-ADUser -Identity $_.SamAccountName -SurName $_.SurName}
$users | Foreach {Set-ADUser -Identity $_.SamAccountName -Description $_.Description}
$users | Foreach {Set-ADUser -Identity $_.SamAccountName -Manager $_.Manager}
#$users | Foreach {Set-ADUser -Identity $_.SamAccountName -Office $_.Office}
#$users | Foreach {Set-ADUser -Identity $_.SamAccountName -Department $_.Department}
#$users | Foreach {Set-ADUser -Identity $_.SamAccountName -Title $_.Title}

I would be obliged if someone could help me out.

Regards

Disable AD Computer from txt file and move it to target OU

$
0
0

This is the script I have, but something is not right.

 

Import-Module ActiveDirectory

$computers = get-content "C:\disabled computer.txt"

foreach-object{

$computer | disable-adaccount

$computer | move-adobject -targetpath "ou=Disabled computers,dc=Domain,dc=com"

write-host “$computer will be moved to Disabled Computer OU”

}

 

Anyone can help?

Thanks

AD member list Script

$
0
0

First time posting but hello there users!

I am novice, at best, and I was wondering if I could get a script that shows all the users of a certain security group while also filtering it to only show users that are older than 5 months.  

 

Context: I would like to show users that are part of an exclusion group that have been with us for longer than 5 months so I can go ahead and remove them from that list.

 

Thank you and all responses appreciated :D

Viewing all 10624 articles
Browse latest View live