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

Custom attribute not shown

$
0
0

Hi, I extended the user class in Active Directory with an additional attribute -> "CostCenter". When i check a user object with ADSIEDIT, i can see the custom attribute. However when i get the user object with Powershell, I cant find the attribute.

I used: 

Get-aduser %SamAccountName% -server Contoso -properties * | fl cost*

Get-ADObject -Filter 'Name -Like "*%SamAccountName%*" -Server Contoso -Propeties *

'


Answers provided are coming from personal experience, and come with no warranty of success. I as everybody else do make mistakes.


Reading temporary data from workstations

$
0
0

Good morning,

First I'm not a programmer, I write some code but looping gets me one loop is easy two loops gets me.  I will first explain what I'm trying to do and then show you my code.

I'm trying to write a script to clean temporary files on workstations, they do not want this to run this as a logon or logoff script thus complicating matters as I cannot use variables to clean up the user profiles on these remote workstations.  This will be run every Sunday.

$a = Get-Content "C:\CSD\Scripts\PLSCAAD_PC_List_Test.csv"

 


#foreach ($i in $a)
 
# {Remove-Item "\\$i\c$\temp\*" -force -recurse}

#foreach ($i in $a)
 
# {Remove-Item "\\$i\c$\windows\temp\*" -force -recurse}


foreach ($i in $a)

{Get-ChildItem "\\$i\c$\users" | Where-Object {$_.PSIsContainer} | Foreach-Object {$_.Name}}

The problem I'm having is storing that last Get-Childitem into a variable.  If I put a $USERPROFILE= in front of that I get an error.  I need to store that list of directories of users into a variable and then write a for each statement against it.  My goal is to clear different temp directories from the users profile.  The rest of the directories are not a problem.

I know that code isn't the cleanest...  I would prefer not to have so many loops in there, but I'm not that good at this sort of thing.  I've managed to be more of a hardware/server admin guy.  I write simple scripts that for example to pull BIOS versions or serials from our servers but we have got other software now that does some of this stuff, although I do write scripts still for drive space.  It's really these loops, I don't know why I have such a block with them but the light bulb has not gone off yet.

Thanks in advance,

Tim

.

$_ '-msDS-cloudExtensionAttribute1' attribute not recognised?

$
0
0

Hi - I am trying to populate the  -msDS-cloudExtensionAttribute1  field in users AD accounts with their givenname_surname

Import-Module ActiveDirectory 
Get-ADUser -filter * -Searchbase "OU=temp,OU=users,DC=mydomain,DC=test" | 
ForEach-Object{ 
set-ADUser $_ '-msDS-cloudExtensionAttribute1' ($_.givenname + "_" + $_.surname)
}

But, I am having trouble referencing the -msDS-cloudExtensionAttribute1  field??
Apparently I have to use single quotes because the attribute itself had a hyphen

Error message: Set-ADUser : A positional parameter cannot be found that accepts argument '-msDS-cloudExtensionAttribute1'

Where am I going wrong please?
Thank you

How can I add a member to an AD Group by passing an object property?

$
0
0
Function CreateUser($fname,$lname)
{
$0bj = New-ADUser -name "$fname $lname" `
            -GivenName $fname `
            -Surname $lname `
            -DisplayName "$fname $lname" `
            -SamAccountName $fname `
            Add-ADGroupMember -Identity grp_sales -Members $Obj.SamAccountName

} 

Hi,

How can I add a user to an AD Group by passing the SamAccountName property value?

e.g.

I am trying to create a function that creates a new user and adds them to a group.

But when I try to assign the $Obj variable with the new user, it is telling me that the Add-ADGroupMember -Members parameter can't accept a Null Value.

Is it possible to do something like this? 

Thanks  

 

send active directory password rule via an email

$
0
0

Hello

Can anyone help me scripting, we would like to send out an automated email to all mgmt heads about the AD password rules.

Thanks

Naveen Rao

Traverse through events in Security logs generated after the last event read instead of the entire Security log.

$
0
0

Here is a script that will filter events from Security logs for Logon types and the primary focus here is that the below code should output results or should execute on the logs generated after the last event was read in the last run using EventRecordID. However, the script executes without errors but gives the same output each time. If there have been no relevant logs generated since the last run which meet my requirements, it should rather not produce any output or should give me latest records only. Please HELP!!

Try {
    $_intMyRef = [int] (Get-Content c:\test\ref.txt)
}
Catch {
    Write-Host "The reference EventRecordID cannot be found." -ForegroundColor Red
    $_intMyRef = 0
}

$logFile = 'C:\test\test_excel_try.csv'
$myOU = "OU=ABC,dc=contosso,DC=com"
$Computer = "XYZ"
$logontype = @{ # LogonType as per technet
    2 = "Interactive" 
    3 = "Network"
    4 = "Batch"
    5 = "Service"
    7 = "Unlock"
    8 = "NetworkCleartext"
    9 = "NewCredentials"
    10 = "RemoteInteractive"
    11 = "CachedInteractive"
}
$Result = @()
Get-WinEvent -FilterXml "<QueryList><Query Id=""0"" Path=""Security""><Select Path=""Security"">*[System[(EventID=4624 and EventRecordID&gt;$_intMyRef)]]</Select><Suppress Path=""Security"">*[EventData[Data[@Name=""SubjectLogonId""]=""0x0"" or Data[@Name=""TargetDomainName""]=""NT AUTHORITY"" or Data[@Name=""TargetDomainName""]=""Window Manager""]]</Suppress></Query></QueryList>" -ComputerName $Computer | ForEach-Object {
        $Event = $_ | select *
        $curOU = ([ADSI]"LDAP://<SID=$(($Event.Properties[4]).Value.Value)>").distinguishedName # TargetUserSid
        If ( $curOU -like "*$myOU" )
        {
            $Props = @{ 
                OU = $curOU.ToString();
                LogonType = $logontype[ [int] $Event.Properties[8].Value ];
                TimeCreated = $Event.TimeCreated;
                SourceNetworkAddress = $Event.Properties[18].Value
            }
            $LogonRecord = New-Object -TypeName psobject -Property $Props
            $Result += $LogonRecord
            $_intLastId = $Event.RecordId
        } 
    } 
$Result | Export-Csv -Path $logFile -append -UseCulture -NoTypeInformation # Log it to CSV
Write-Output $_intLastId | Out-File c:\test\ref.txt

get-childitem to list directories, but only if they have an extension

$
0
0

I know how to use GCI. I know how to use it to list directories only, but how can I use it to list directories that have an extension?

I'm guessing it's going to be something along the lines of

gci -Directory | Where-Object {$_.Extension -eq $true }

But that doesn't work.


zarberg@gmail.com

get-adgroup -filter * | I want to get more than just SAMAccountName properties --- I am getting greedy :-)

$
0
0

Hello,

PowerShell maestro Mike Laughlin helped me develop this .ps1 script which gathers a .csv list of all AD groups with all their AD user account members (GROUP <group name> and MEMBER <SAMAccountName>) and it works very well.  I am getting greedy and want to .csv export even more information on the AD user account properties.  Based on the .ps1 below, how/if can I modify this script to get even more AD group member AD user account properties such as:

  GROUP                         MEMBER                          USER NAME                     ENABLED              LAST LOGON

<group name>         <SAMAccountName>             <DisplayName>                <Enabled>          <LastLogonDate>

I am getting more impressed with PowerShell v4.0 capabilities and the more I automate the more greedy I want to do more.  

Thanks to all PowerShell superstars for lending your expertise on this Windows PowerShell forum!


Matt


Create user in ADAM instance with powershell

$
0
0

Hi

I was wondering if you could help me with the ability to create a user in AD / Adam? I am trying to write the powershell code to create users for Teradata connectivity. the manual process is to use adsiedit and create the users through groupof names class.

This is what I have that is NOT working and was looking where to go from here.

$dom=[ADSI]"LDAP://OU=Users,OU=dev,OU=tdev,dc=acme,dc=com"
$obj = $dom.Create('GroupOfNames', 'CN=ASmith')
$obj.SetInfo()

any help would be greatly appreciated.

Thank you

Script takes too long to filter results from Security logs..

$
0
0

Here is a script that takes more than 20 minutes to give me results for the latest 5 minutes from Security logs. The size of security logs before it overrides is 1 GB in about 40 minutes. The script filters Interactive logon or type of logon from the security logs for a specific OU users. This run time isn't feasible. Please suggest what is taking so much time and if some loops need improvements.Any help will be highly appreciated!!!!

logFile = 'C:\test\test.csv'

$myOU = "OU=ABC,dc=contosso,DC=com"
$Computer = "XYZ"
$Minutes= 5
$logontype = @{ # LogonType as per technet
    2 = "Interactive" 
    3 = "Network"
    4 = "Batch"
    5 = "Service"
    7 = "Unlock"
    8 = "NetworkCleartext"
    9 = "NewCredentials"
    10 = "RemoteInteractive"
    11 = "CachedInteractive"
}
$Result = @()
$Duration = ((Get-Date).AddMinutes(-5))
Get-WinEvent -FilterXml "<QueryList><Query Id=""0"" Path=""Security""><Select Path=""Security"">*[System[(EventID=4624)]]</Select><Suppress Path=""Security"">*[EventData[Data[@Name=""SubjectLogonId""]=""0x0"" or Data[@Name=""TargetDomainName""]=""NT AUTHORITY"" or Data[@Name=""TargetDomainName""]=""Window Manager""]]</Suppress></Query></QueryList>" -ComputerName $Computer |
    Where-Object { $_.TimeCreated -ge $Duration } |
    ForEach-Object {
        $Event = $_ | select *
        $curOU = ([ADSI]"LDAP://<SID=$(($Event.Properties[4]).Value.Value)>").distinguishedName # TargetUserSid
        If (( $curOU -like "*$myOU" ) -AND (($logontype[ [int] $Event.Properties[8].Value ]) -like "Interactive")){
            $Props = @{ 
                OU = $curOU.ToString();
                LogonType = $logontype[ [int] $Event.Properties[8].Value ];
                TimeCreated = $Event.TimeCreated;
                SourceNetworkAddress = $Event.Properties[18].Value
            }
            $LogonRecord = New-Object -TypeName psobject -Property $Props
            $Result += $LogonRecord
        } 
    } 
#if ($Result) { Write-Host "Results from the past $days days:" -ForegroundColor Green }
 #   else { Write-Host "No new results from the past $days days" -ForegroundColor Yellow }
#$Result | select -Unique # See it on the console
#$Result | select -Unique | Out-GridView # See it in ISE GV
$Result  | Export-Csv -Path $logFile -append -UseCulture -NoTypeInformation # Log it to CSV

Also, if I use Select -unique with my excel result. It gives me a single entry which should not be the case. It should give me unique entries for a DN used in a specific. However, i would like to concentrate on the run time primarily.

Can someone please help me extract all users, but properties of one AD attribute?

$
0
0

Hi everyone. We use the pager field in AD for printer pins. I'd like to extract a list of all the users, with the properties of the pager field to a csv file. The reason is that we can't duplicated pins, so need to keep track of which ones are used and then ensure we always assign a unique one to new users.

the powershell;

get-aduser sbryan -properties *| select -property pager
lists it for me, in the powershell window, but if anyone can help me with the command for all users, plus list the value of that pager field, that would be great.

thanks in advance, Shane.


 

Access denied when importing a certificate

$
0
0

Hi,

I get an Access denied error when trying importing a certificate.

PS C:\Deploy\Licenses> Import-Certificate -FilePath "C:\Deploy\Licenses\Certificates\somecertificate.cer" -CertStoreLocation Cert:\CurrentUser\CA

Import-Certificate : Access is denied. 0x80070005 (WIN32: 5 ERROR_ACCESS_DENIED)

At line:1 char:1
+ Import-Certificate -FilePath "C:\Deploy\Licenses\Certificates\Thawte crossca.cer ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Import-Certificate], Exception
    + FullyQualifiedErrorId : System.Exception,Microsoft.CertificateServices.Commands.ImportCertificateCommand

I start the powershell prompt with Run as different user and key in the user credentials. The user is Administrator on the box, UAC is disabled and ExecutionPolicy is set to Unrestricted. The prompt includes Administrator so i guess the prompt is elevated.

What else needs to be set to provide the user appropriate access?

Thanks

Delete folders older than X days via SQL Agent Job

$
0
0

I've been trying to run the script below which is on my disk via a SQL Agent job with parameters but it just runs forever and never deletes any content.

# Set limit -x days
$limit = (Get-Date).AddDays(-$LimitDay)

# Path to Recurse
$path = "$TargetPath"

get-childitem -Path $path -Recurse -Force |? {$_.psiscontainer -and $_.lastwritetime -le $limit} |% {remove-item $_ -force -whatif}

In the SQL job I would enter;

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe c:\sysadmin\scripts\backuptrim.ps1 -TargetPath\\server1\foldername\Daily -LimitDay 14

I've also tried running the SQL job step as Operating System cmdshell and the PowerShell option.  The SQL service accuont has full control access to the share and underlying folders too.

Any ideas? - thanks

Start-Process : This command cannot be run due to the error: The system cannot find the file specified.

$
0
0

Hi, 

I need some help with my script. It copies the file to the remote laptops but when it needs to install the .exe it fails.

If I run 1 line at the time in Powershell ISE, then it works. Somebody has an idea why it doesn't work or can help me on the right way?

Script: 

    

$laptops = Get-Content -Path "C:\Users\bruyld01\Documents\STEPSTONE\Powershell\SAP\LaptopList.txt"

foreach ($laptop in $laptops)
    {
    Copy-Item "C:\Users\bruyld01\Desktop\SAP_Business_ByDesign_Add-In_for_Microsoft_Outlook_V5.exe" -Destination \\$laptop\C$\
    Enter-PSSession $laptop
    $version = Get-WmiObject -Class Win32_Product | where {$_.Name -like "*SAP Business*"} | Select-Object Version

    if ($version -ne "135.0.2071.1047")
        {
        Start-Process -Filepath "C:\SAP_Business_ByDesign_Add-In_for_Microsoft_Outlook_V5.exe" -ArgumentList "/quiet"
        }
    else
        {
        Write-Host "SAP outlook add-in is up to date!" -ForegroundColor Green
        }

    Exit-PSSession
    }


Error message:

Start-Process : This command cannot be run due to the error: The system cannot find the file specified.
At line:2 char:1
+ Start-Process -Filepath "C:\SAP_Business_ByDesign_Add-In_for_Microsoft_Outlook_V ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Start-Process], InvalidOperationException
    + FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand

Thanks, 

Dimitri

Get-Childitem with millions of files

$
0
0

Hello all,

My task is to create a report with all subfolders in a given path, sorted after the newest LastWriteTime on any file in the folder.
The ultimate reason is to determine which folders have been unused for long enough to move to offline storage.

So far I've come up with this:

Get-ChildItem $folderpath | Where {$_.PsIsContainer} | foreach-object { Get-ChildItem $_ -Recurse -ErrorAction SilentlyContinue | Where {!$_.PsIsContainer} | Select Name,DirectoryName, LastWriteTime, Mode | Sort LastWriteTime -descending | select -first 1}|export-csv $drive:\report.csv

I know this works, I've tested it on a couple of folders.
The problem is that the folder I really want to run the report for contains approximately 6.5 million files in many thousands of subfolders. Memory usage goes through the roof, server gets unresponsive, I have to kill the script before users get angry.

I suppose that PowerShell tries to create an array in memory before actually piping and sorting, and that's the reason for the memory problem.

Is there a smarter way to do it?



Performance of "Get-PartitionSupportedSize" on 2012 R2

$
0
0

Hi,

I'm running at Server 2012 R2 file server cluster on VMs, using shared VHDXs. I have scripted a process for expanding a shared VHDX (basically, detaching the VHDX from all nodes, adding space, reattaching, then extending the volume). It would be easiest to use the Get-PartitionSupportedSize to extend the volume, but this command takes just about forever to return a value. Is anyone else seeing this sort of slow performance?

My alternative is to use DiskPart, which extends the volume right away. The downsize to DiskPart is that I need to parse the output of "list vol" | DiskPart to determine a volume number for the command "sel vol #","extend" | DiskPart. Obviously, this can be done, but I worry that I will screw it up--especially because I want my input script to accept drive letter, file system name, or mount point.

Is there a better way to do this? Better yet, none of this would be necessary if shared VHDXs could be extended online--anyone heard of that feature coming down the pipe? 

Thanks!
Matthew


Matthew

Need to use -credential in get-wmiobject

$
0
0

Hi,

I would like to remotely enumerate printers on our 2012r2 print server from a Windows 7 box. I am logged into the Win7 box with a domain account that is in the local admins group on the print server. When I:

  get-wmiobject -class "Win32_Printer" -computer printserver.college.edu

I get the dreaded 0x80070005 access denied. If I add "-credential DOMAIN\user" (where DOMAIN\user is the account I am already logged into the Windows 7 box with) and enter my password when prompted, it works fine (so I am sure DOMAIN\user has the proper authority on the print server to do this). I've tried this from the PowerShell console/command line as well as in the ISE with the same results.

What's going on here? Thanks, Tony

Help! I need a simple powershell command to display all folders & files over the 260 char limit

$
0
0

Can anyone help me please? I'm trying in vain to identify any files or folders I have in a directory over the 260 char limit.

my powershell knowledge is quite limited so I've hit the wall with ideas.

Any help appreciated.

Thanks

Powershell - Copy a list of files to multiple servers and backup exisiting files

$
0
0

Hello..

I would like to have assistance from Powershell gurus..

My scenario is; I want to automate a task to copy some .dll files from one location to multiple servers but before copying those files over to those servers; I'd like to take a backup for those same files which will be overwritten on to a local server where these .dll files will be copied from

My preference would be that the script should read 1 file (.txt or .csv) which will contain the name of those files that need to be copied over and get backedup and then read another file which will contain the list of servers.

example

File to copy = filename.dll (this filename.dll should be read from a .txt or .csv file which could contain more than 1 file)

Server to copy to = server1, server2, server3 (this should be read from a .csv file)

From the local server; Read filename(s).dll from the file, the servername from the server file and before copying the new files over, copy those exact same files from the shared folders on those servers and paste them on the local server by creating a folder as the servername and paste the file in there.

Then copy the new files over to those servers from the list and overwrite the existing files.

I really appreciate your time and effort in this

Thanks

Get Password Not Expire From Script

$
0
0

I'm currently working with this script and I would like to add password does not expire in the .csv to either true or false if that box is checked. Can you guys help?

$NumDays = 0
$LogDir = ".\Users-Last-Logon.csv"

$currentDate = [System.DateTime]::Now
$currentDateUtc = $currentDate.ToUniversalTime()
$lltstamplimit = $currentDateUtc.AddDays(- $NumDays)
$lltIntLimit = $lltstampLimit.ToFileTime()
$adobjroot = [adsi]''
$objstalesearcher = New-Object System.DirectoryServices.DirectorySearcher($adobjroot)
$objstalesearcher.filter = "(&(objectCategory=person)(objectClass=user)(lastLogonTimeStamp<=" + $lltIntLimit + "))"

$users = $objstalesearcher.findall() | select `
@{e={$_.properties.cn};n='Display Name'},`
@{e={$_.properties.samaccountname};n='Username'},`
@{e={[datetime]::FromFileTime([int64]$_.properties.pwdLastSet)};n='Password Last Set'},`
@{e={[datetime]::FromFileTimeUtc([int64]$_.properties.lastlogontimestamp[0])};n='Last Logon'},`
@{e={[string]$adspath=$_.properties.adspath;$account=[ADSI]$adspath;$account.psbase.invokeget('AccountDisabled')};n='Account Is Disabled'}


$users | Export-CSV -NoType $LogDir

Viewing all 21975 articles
Browse latest View live


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