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

Get members list from multiple AD groups

$
0
0
Hi,

Please help me out. What I'm doing is importing 16 AD groups in a PowerShell script and finding the list of users in those AD groups. I am doing this for audit purpose. 

Since I'm exporting the user list for 16 AD groups, the -append parameter is making the list of users in the output file appear one next to it and I couldn't figure out which user belongs to which group, since there are 450 to 500 users in the output file. I need some changes in the below script so that each user appears with the group name for which it is extracted. 

Example- script run for first AD group- lists 4 users in that AD group. The script runs again for another AD group, this should display with the users' list along with the Group name which is trying to export the list. Hope I am not complicating it. Please help me out.


$groups = Get-content -path "C:\Users\Santosh\OBIP.csv"
foreach ($GroupName in $groups) 
{
Get-ADgroupmember -Id $GroupName -Recursive | Where objectclass -eq 'user' | Get-ADUser -Properties Displayname,GivenName,Surname,UserPrincipalName,Title,Department,Enabled,ObjectClass, memberof | Select DistinguishedName, samAccountName, Name, Displayname, GivenName, Surname, UserPrincipalName, Title, Department, Enabled, ObjectClass | export-csv -path "C:\Users\Santosh\OBIP\GN.csv" -Append
}

Get the lastest access file date for a directory structure.

$
0
0

Hi guys,

I know my title is not very clear.

Here is my problem, I'm sure that I will figure it out at some point, I've been thinking about this for only 5/10 minutes only but maybe one of you had that problem to solve in the past.

I need to do some cleaning on a file structure (multiple millions of files and directories). The idea is to get the list of file within a folder, find the most recent file accessed in that folder, and create a array which will include the path of that folder, and the timestamp found.

Example:

Folder1
--> file1 accesstime:2018-06-28-15:00 *most recently accessed
--> file2 accesstime:2018-06-28-14:00
--> file3 accesstime:2012-06-28-15:00
------> folder2
---------> file1 accesstime:2016-06-28-18:00 *most recently accessed
---------> file2 accesstime:2014-06-28-14:00
---------> file3 accesstime:2013-06-28-15:00
etc ...

The result:

Folder1 - 2018-06-28-15:00
Folder1/Folder2 - 2016-06-28-18:00

If a folder is empty let the timestamp blank

I though about Get-childitem -recurse, but I'm not sure it will be really helpful, as it is going to spit a list of multiple millions files, and that I will have to recurse that list anyway.

At this point, I'm thinking about doing my own recursive function to crawl the tree, and add the logic to add an array element for each folder, and assign the timestamp after doing a sort on timestamp with in each folder.

Thank in advance for your help

Personne

Need a PS script for Disk

$
0
0

Need a PS script for getting disk information,

Physical disk or San disk and how much free space in the drive

Above details need to get from script


Modify Manager in AD from CSV with plain names (displayname)

$
0
0

Hello everyone,

I am trying to modify the Manager attribute from a CSV file I was given that only has the users "First Last" and the managers "First Last" names in it. I am trying to figure out what the best way to do this is, should I use a separate script to get those names into a CSV that has the samAccountName and DistinguishedName and then just use a simple script to bring that in or is there a way I can modify this script I found from kunaludapi on Github to use DisplayName instead of samAccountName? If I do DisplayName how can I have it search the OU's to find it?

https://github.com/kunaludapi/powershell-change-aduser-manager/blob/master/Update-ADUserManger.ps1

 

Thank you

Multiple switch-Parameters do not work

$
0
0
[CmdletBinding(DefaultParameterSetName='All')]
param(
        [Parameter(
            Mandatory=$true
        )]
        [ValidateLength(5,63)]
        [ValidatePattern("[a-z][.]{1}[a-z]")]
        [string]$DomainName,
        [Parameter(
            ParameterSetName='SecondDC',
            Mandatory=$false
        )]
        [switch]$SecondDC,
        [Parameter(
            ParameterSetName='SecondDC',
            Mandatory=$true
        )]
        [ipaddress]$SecondDCIP,
        [Parameter(
            ParameterSetName='Fileserver', 
            Mandatory=$false
        )]
        [switch]$Fileserver,
        [Parameter(
            ParameterSetName='Fileserver', 
            Mandatory=$true
        )]
        [ipaddress]$FileserverIP
    )

Hi together,

I have a strange problem and unfortunately find nothing to it:

With my parameter-list above I can just use one of my switch parameters.

For example:

test.ps1 -DomainName "test.local" -SecondDC -SecondDCIP 10.0.0.2 #is possible

test.ps1 -DomainName "test.local" -Fileserver -FileserverIP 10.0.0.1 #is possible

test.ps1 -DomainName "test.local" -Fileserver -FileserverIP 10.0.0.1 -SecondDC -SecondDCIP 10.0.0.2 #not possible, Error: "The parameter set cannot be resolved with the specified named parameters." 

Where's my fault, I don't understand...

Thank you for every answer and every help!

Get file owner from Robocopy created text file, output in CSV with full path and owner. Paths longer that 256 characters

$
0
0

I have created a script that uses Robocopy to create a txt file with the full path of every file on a drive (~5 million objects).  I then import that file into a foreach loop and downloaded the module that will allow large file paths (get-ntfsowner) that will iterate through the file paths and spit out the file path and owner in a CSV.  I'm then using that file to run another script our support center will use that will plug all of this in to subinacl to change all the user's file ownerships to their manager when the user leaves the company.

The script runs perfectly, but the problem is finding the owner and creating the CSV's take a few days.  I found that maybe hashtables may help me but I'm pretty much lost on this.  I'm also thinking get-acl would be much faster but I run into the 256 character limit and have spent hours trying to get \\?\ to work with no success.   I'm pretty sure my bottleneck though is the foreach loops slowing things down. 

Can someone help me take this code and make it much more efficient?  I'm trying to get it down to where it will run in an overnight window every night. 

#Gets Owner for each file And Create CSV
$Dir = "D:\AutoAssign\Data\RoboLogs"
$Files = Get-ChildItem $Dir
ForEach ($File in $Files){ Start-Job -ScriptBlock {
    Param($Dir,$Files,$File)

$OutputFile = "D:\AutoAssign\Data\Final\$File.csv"
$Results = @()

$Paths = Get-Content $Dir\$File
ForEach ($Path in $Paths){
 $Owner = get-ntfsowner $Path | Select Owner | ft -hidetableheaders | Out-String
 $Owner = $Owner.Trim()

      $Properties = @{

      Path = $Path
      Owner = $Owner
           
      }

If ($Owner -ne "BUILTIN\Administrators" -and $Owner -ne $null-and $Owner -ne "Domain\Domain Admins" -and $Owner -notlike "S-1*"){
    $Results += New-Object psobject -Property $properties}

    }


$Results | Export-Csv -notypeinformation -Path $OutputFile

} -ArgumentList $Dir,$Files,$File #Ends Initial ForEach

}  #Ends Job Script Block

Exporting a certificate's private key to file (pem, cert, pfx)

$
0
0

I am doing some work with certificates and need to export a certificate (.cer) and private key (.pem or .key) to separate files. I can use theExport-PFXCertifiacte cmdlet to get a .pfx file with a password that contains both the certificate and the key, but I need to have the key as a separate file. Everything that I've found explains how to open the pfx and save the key with OpenSSL, XCA or KeyStore Explorer, but I am looking for a way to do this with just Powershell.

I am getting the .cer file itself through Export-Certificate which is working well, it's just getting the key that I need help with. If there isn't a way to export it through a cmdlet, I could write it to a text file, but I'm not sure how to get the certificate's private key into the text file the correct way. The pem key file would look something like this:

"----BEGIN RSA PRIVATE KEY----""Proc-Type: " + $procType"DEK-Info: " + $DEKInfo
$privateKey"-----END RSA PRIVATE KEY-----"

I'm using Windows Server 2012 R2 & WMF 5.0. Any suggestions?


Automate BIOS password change for ASUS system board using Powershell

$
0
0

Hello all,

I have a project on my hands that I am trying to resolve remotely using Powershell and/or any other means other than having to go find each computer that is out in the field individually. I am looking to change the BIOS password on a Transource MIR-B 1000M. It has an ASUS system board. For the life of me, I cant find the namespace where the BIOS settings can be seen and/or managed. Any help with this would be incredibly appreciated


Powershell script to find users with employee IDs within a specific numerical range

$
0
0

I need a powershell script to find user accounts whose employee ids do not lie in the range of 10000000-99999999.

For this I wrote a script, however, it seems it is running for ever without returning any result.

Script is given below :

$employeeids = 10000000..99999999

Get-ADUser - Filter {EmployeeID -like "*"} -Properties * | Where-Object {$_.employeeid -notin $employeeids} | FT SAMAccountName,EmployeeID

We have around 80 thousands user accounts and the script is not all helping to fetch the required details.

Can someone please help me to fix this?

Regards,

Raj

Run WindowsUpdate.diagcab silently

$
0
0

Hello to all, 

Is anyone knows how to run WindowsUpdate.diagcab  silently with Powershell?

I have tried running it on Windows 7, with no success. 

WU.diagcab file

I have tried a suggestion from the replies (DanielKoschelewitsch) and got an error message: 

LinkToForum

Powershell.exe -nologo -executionpolicy unrestricted -command c:\ps\automatedfixunattended.ps1 c:\ps\windowsupdates.diagcab"The script only help you silently use the automated fix solutions with the '.mini.diagcab' extension"

What is that mean only mini diagcab? 

Thanks

Amir

SCRIPT NOT RUNNING

$
0
0

Hello all,

I have created a small powershell script to clear the content using the exe file.

It executed without any error, but when I check the respective logs the exe is not triggered during the execution.

$computerlist = Get-Content -Path c:\temp\input.txt

foreach ($computername in $computerlist)

{
$filelist = Get-Content -Path C:\temp\list.txt
ForEach ($value in $filelist)
{
$contentname, $contentversion = $value.Split(",")
$command = "'C:\program files\1e\nomadbranch\cachecleaner.exe' -deletepkg=$contentname -pkgver= $contentversion"


$process = [WMICLASS]"\\$computername\ROOT\CIMV2:win32_process" 
$result = $process.Create($command)



}

Plese correct the script.

Thanks 

Suresh M


THANKS SURESH M

Fonts Installieren mit Powershell

$
0
0
Hi leute :D

Ich suche mir jetzt mal wieder seit längerem die finger wund auf der suche nach einem geeigneten quellcode, womit ich fonts installieren und überschreiben kann.
Ich bin ein newbie und versuche mich damit auch immernoch aus.
der folgende Quellcode den ich gefunden habe ist aus meiner sicht ein guter anfang, nur sucht er an der ganz falschen stelle nach den zu installierenden fonts... könnt ihr mir vll weiter helfen?

Start-Process powershell -verb runas  { $ssfFonts = 0x14
$fontSourceFolder = "pfad meiner zu installierenden fonts"
$Shell = New-Object -ComObject Shell.Application
$SystemFontsFolder = $Shell.Namespace($ssfFonts)
$FontFiles = Get-ChildItem $fontSourceFolder
$SystemFontsPath = $SystemFontsFolder.Self.Path
$rebootFlag = $false

foreach($FontFile in $FontFiles) {
	# $FontFile will be copied to this path:
	$targetPath = Join-Path $SystemFontsPath $FontFile.Name
	# So, see if target exists...
	if(Test-Path $targetPath){
		# font file with the same name already there.
		# delete and replace.
		$rebootFlag = $true
		Remove-Item $targetPath -Force
		Copy-Item $FontFile.FullName $targetPath -Force
	}else{
		#install the font.
		$SystemFontsFolder.CopyHere($FontFile.fullname)
	}
}

#Follow-up message
if($rebootFlag){
	Write-Host "At least one existing font overwritten. A reboot may be necessary."
}
}

Danke schonmal :D

Run Powershell script as Scheduled task, that uses Excel COM object

$
0
0

What am I missing here..

 

I have  Powershell script that uses the Quest AD cmdlets to get computer information from AD and populate an Excel spreadsheet with the data.

The script works fine, so I created a batch file and started the script from there (which works fine as well). It populates the excel spreadsheet, saves and closes the file.

If I run the script as a scheduled task, I can see from the logging that it supposedly gets the computers from AD, and runs through them. But a file is never saved, I have tried to run the scheduled task with admin credentials.

What am I forgetting?

Get a report of No members of a Distribution Group

$
0
0

Hello team !!

I've been trying to get a report of users that don't belong to a certain Distribution List in Office 365, something like this , but just the opposite, no menbers instead of members:

Get-DistributionGroupMember -ResultSize unlimited grupo1@dominio.com | select DisplayName, PrimarySmtpAddress | Export-Csv C:\grupo1.csv -NoTypeInformation

Any ideas ??

thanks in advance

germain 

set-aduser zip code for bulk users

$
0
0

i try to update the zip-code for active directory users as the below 

# Import AD Module             
Import-Module ActiveDirectory 
$users = Import-Csv -Path C:\zip.csv
# Loop through CSV and update users if the exist in CVS file            
foreach ($user in $users) {
Get-ADUser -Filter "SamAccountName -eq '$($user.Username)'" 
Set-ADUser -PostalCode $($user.zipcode)
}


Ahmed Zidan Network Administrator


Does a new version of my module need a new GUID in it's manifest?

$
0
0
I have a module and manifest that I created using New-ModuleManifest.  I can copy and modify the manifest from the previous version and just change the value for ModuleVersion?  Or do I need to generate a new GUID too?

Invoke-Command to run a command on a remote server

$
0
0

Hello, I am trying to run a invoke-command on Computer1 to run a powershell script that's in Computer 1.  The powershell script in Computer1 has a line "get-content "\\Computer2\c$\test.txt".

I get cannot find-path error so on I logged in to computer1 and ran "get-content "\\Computer2\c$\test.txt" and it worked fine.

I went back to my desktop and ran

Invoke-Command -ComputerName "Computer1" -ScriptBlock { get-content "\\Computer2\c$\test.txt"}

I get cannot find-path error. 

why does this not work?

Thank you


Unable to Remove Groups from AD User

$
0
0

Hi All,

I am trying to remove Groups from a users account using the below script. But somehow it says it cannot remove.

What could be the issue.

$SamAccountName = "SamacountName"
$Groups = "Grp1;Grp2;Grp3"

$GroupArray = $Groups.Split(';')

foreach ($item in $GroupArray){
try {

    Remove-ADGroupMember -Identity $item -Members $SamAccountName
    }  
catch 
    {
	"Group Name:$item not able to remove from EmpID :$SamAccountName"
    }
}


Justin

Get-ACL error on AD objects under OU with colon in the name

$
0
0

Hello all,

I am having an issue with the Get-ACL cmdlet where it cannot parse sub-objects underneath a System Container with a colon in the name (e.g.CN=Microsoft,CN=1:1,CN=Pools,CN=RTC Service,CN=Microsoft,CN=System,DC=contoso,DC=com).

However, Get-ACL can parse the container itself (including the colon) just fine.

This is true not just for Containers, but for OU's as well. For example:

#works fine on "colon" object itself
get-acl -Path "AD:OU=System:Stuff,DC=contoso,DC=com"

#FAILS when asking for sub-object under "colon" object
get-acl -Path "AD:CN=TestUser123,OU=System:Stuff,DC=contoso,DC=com"

I have tried -LiteralPath also, and all kinds of combinations of escapes, single quotes, Join-Path, etc. with no luck.

Any thoughts on how to get the second command above to work?

CGI Hosting?

$
0
0

I'm interested in being able to host PowerShell scripts as CGI applications on my IIS web server.

I tried setting this up in much the same way as I would with PHP, Perl, or Python, just creating a mapping from ".ps1" files to "C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe", but whenever I try and visit my /cgi-bin/test.ps1 script (which just spits out a "Hello World!") I get:

"CGI Error

The specified CGI application misbehaved by not returning a complete set of HTTP headers."

Which is the same error I received when I had Python running improperly setup.

Anyone care to help me out?

Running IIS 6.0 on Windows Server 2003 SP2 64-bit.

P.S.: I also tried setting up PowerShell through FastCGI, using the configuration script provided with FastCGI, but whenever I tried to visit my /cgi-bin/test.ps1 I would receive a FastCGI error stating that the process terminated unexpectedly.

Viewing all 21975 articles
Browse latest View live


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