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

Powershell to Enable "Protect from Accidental Deletion" on ALL OU's

$
0
0

Howdy folks...

The client I am currently working with has partially set the "Protect from Accidental Deletion" attribute on their AD...I want to extend this feature to ALL organisation units (OUs) in their forest (but only to the OUs and nothing else). I know how to use PS to do for ALL objects however, I'm having problems with the "Filter". I've attempted the following command (and various iterations) but they seem to fail on the filter;

Get-ADobject -Filter "organizationalUnit" -SearchBase “OU=OU1,DC=DomainComponet2,DC=DomainComponent1” | Set-adobject -ProtectedFromAccidentalDeletion $true

Does anyone know what the { -Filter "organizationalUnit" } part should be...?

Rgds

FMcFF


find list of local Administrators in all server of domain

$
0
0

Hi Team,

I have around 1000 server running in my domain, I need to find out Member of local administrator in all the servers of domain. do we have any script which can full fill my requirement.  ?



Regards, Triyambak

How to Compare 2 CSV file and store the result to 3rd csv file using PowerShell script?

$
0
0

I want to do the below task using powershell script only.
I have 2 csv files and I want to compare those two files and I want to store the comparision result to 3rd csv file. Please look at the follwingsnap:


This image is csv file only. 

Could you please any one help me.
Thanks in advance.
By
A Path finder 
JoSwa


If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful"Best Online Journal


Need help with writing comments before executing function

$
0
0

Hello all,

i have below code i need to write comment before executing function.

        [Parameter()][string]  $Backuppath= ( write-host "Enter Backuppath"Select-FolderDialog ) ,#  (read-host "Enter Backuppath"),
        [Parameter()][string]  $SQLTEMPDBDIR=( write-host "Enter Backuppath"Select-FolderDialog ) ,#(read-host  "Enter TempDir"),
        [Parameter()][string]  $SQLUSERDBDIR=( write-host "Enter Backuppath"Select-FolderDialog ) ,#(read-host  "Enter User Data Directory"),
        [Parameter()][string]  $SQLUSERDBLOGDIR=( write-host "Enter Backuppath"Select-FolderDialog ) ,#(read-host  "Enter User Log Directory"),

its not running function Select-FolderDialog its considering function as comment below is the result i am getting  when i execute

Enter Backuppath Select-FolderDialog
Enter Backuppath Select-FolderDialog
Enter Backuppath Select-FolderDialog
Enter Backuppath Select-FolderDialog

can someone help me on this 

AD ACE Script

$
0
0

Hi,

Powershell formatting... I have an incredible headache.  Anyways, what I'm trying to do seems easy enough, but I've just spent hours on trying to format it correctly.

We have a ton of mail enabled groups that are broken because of Exchange 2010 now (thanks for that) because our dept. used ACLs/ACEs with the Write Members property.  That worked fine on Exchange 2003 & Outlook, but no more.

I now have to parse our AD, find any and all users & groups that have that specific property and pipe it to something usable.  It's the "something usable" I just can't get working.

Here's the script:

Import-Module ActiveDirectory
$MailEnabledGroups = Get-Group -OrganizationalUnit "whateverOU" -Filter 'WindowsEmailAddress -ne $null'
$MailEnabledGroups | Foreach-Object {
                Set-Location AD:
                Get-Acl $_.DistinguishedName | select -exp Access | ?{$_.ObjectType -match 'bf9679c0-0de6-11d0-a285-00aa003049e2' -and $_.ActiveDirectoryRights -match 'WriteProperty' -and $_.IdentityReference -notmatch 'Exchange Windows Permissions'}
}

So this gives me correctly all the users or groups that have that exact property, but I'm just trying to extract the group displayname & the identityreference of the account.

I've tried with Select, Format-Table... I just don't have the expertise in PS to get this right at all.  something like | ft displayname,identityreference sorta gives me the info, but it puts the displayname of the group as a header, and if I use -hidetableheaders, then I lose completely the group name I need to keep.  Then there's Select that just won't ever show me the group correctly or just jumbles all identityreference names in 1 big column without knowing which group they in the ACE of.

Once I get that, it's just a matter of piping group + accounts back in the set-distributiongroup and use -managedby to target the accounts I find with get-acl.

I'm aware there's tools out there that work a whole lot better than get-acl, but I do not have authorization to install/use non standard modules on our servers...

Hell, at this point, I'll even take VBS ot a batch file :P if it can get what I need, but I've been trying to use Powershell a lot more... getting information isn't a bit problem, it's the formatting of how to spit out the information that is a massive headache for me still

It's probably some silly combination or format-table commands or whatever, but I definitely can't put my finger on it... any help on this would be greatly appreciated.

Thank you.

Merge XML

$
0
0

I have split up what is going to be a very large amount of XML data into multiple files for long term maintenance reasons. However, I need to combine all this information into a single XML object for use by my code. I tried the expediant of a foreach loop, reading each XML file into a temp variable and using

$global:ResourceXml += $TempResourceXml.InnerXml

However, this produces an XML object that no longer works, and I am trying to determine if I can't merge this way, or I need to access the merged data differently, or... At the memento I am not even sure exactly what is wrong, as I can't get a clean XML to the screen, and my code dumps into an endless loop now, erring on a SelectSingleNode attempt on the newly merged data. Gack.

Any thoughts greatly appreciated.
Gordon

Possible to run advertised programs with Powershell

$
0
0

Hi all so where I work we re-image the machines about every 6 months typically we log into them, go to control panel and select from 2 images (advertisements x64 or x86). My question is could I automate this somehow? Is there an object or a way to call advertised programs and then slect one of them.

Thanks for any help!

How do I get to the IIS prompt

$
0
0

How do I get to the IIS prompt:

PS IIS:\>


Append a top line to multiple txt files

$
0
0

Hi there,

I have to manipulate txt files in powershell and I may not be very good at it... so any help is welcome ^^

I've got multiple files in a single folder. They are exports from a DB and are formatted like that :

"name1"
"name2"
"name3"

I need them to be :

=1
name1
name2
name3

In short I have to remove all the quotes and add "=1" on the first line of each file.

Here's what I've got so far :

$fileEntries = [IO.Directory]::GetFiles("C:\temp"); 
foreach($fileName in $fileEntries)
{
(Get-Content $fileName) |
Foreach-Object {$_ -replace '"', "" } | 
Set-Content $fileName
}


foreach($fileName in $fileEntries)
{
Write-Output "=1`n" | Out-File $fileName -Append
}

It appends at the last line, I just can't get the "=1" at the top... any help would be much appreciated !
Thanks !

Remove all groups from one user

$
0
0
I need a Powershell script using native or Quest cmdlets to remove ALL groups from a user in AD. Now here's the catch, the user is a member of groups from 3 different trusted domains in a single forest. I can get a script to remove groups from the domain the user resides in but it fails on removing the groups from the other domains. Any suggestions? I see this is can be an issue when a user is a member of cross-domain groups but have not found a solution yet.

What is not explicitly allowed should be implicitly denied

Create a child or subdomain in a field or domain

Run 5 commands in parallel using scriptblock

$
0
0

Hi,

I have an array of 10000 commands that I want to process through an application, but only 5 commands in parallel at the same time. So I will take 5 commands from the array $arrCommands, then run those in parallel, then take another 5 commands..process..and so on.. I might have to use "scriptblock" functionality, but with current setup the chance is it will try to run thousands commands in parallel which will actually kill the server. I won't use "Foreach -parallel" because my server running Powershell V2.

Can anyone suggest how can I use scriptblock functionality to receive and process 5 commands in parallel?

----


## Function to process commands
Function ProcessCommands
{
param
(
[string]$ParamCommand
)

[hashtable]$Return = @{}

    $objProcess = New-Object System.Diagnostics.Process
    $objProcess.StartInfo = New-Object System.Diagnostics.ProcessStartInfo

    $objProcess.StartInfo.FileName = "\\OFCAPPSRVR\apps\calcrun.exe"
    $objProcess.StartInfo.Arguments = $Parameter
    $objProcess.StartInfo.UseShellExecute = $shell
    $objProcess.StartInfo.WindowStyle = 1
$objProcess.StartInfo.RedirectStandardOutput = $true

$null = $objProcess.Start()
$objProcess.WaitForExit()

$ExitCode = $objProcess.ExitCode
$StandardOutput = $objProcess.StandardOutput.ReadToEnd()
$objProcess.Dispose()

$Return.ExitCode = $ExitCode
$Return.StandardOutput = $StandardOutput

Return $Return
}


## Main
$arrCommands =@(
"STD -iMXB9010 -o\\OFCAPPSRVR\outputs\MXB9010.pdf",
"STD -iMXB6570 -o\\OFCAPPSRVR\outputs\MXB6570.pdf",
"STD -iMXB8010 -o\\OFCAPPSRVR\outputs\MXB8010.pdf",
"STD -iMXB5090 -o\\OFCAPPSRVR\outputs\MXB5090.pdf",
"STD -iMXB2440 -o\\OFCAPPSRVR\outputs\MXB2440.pdf",
.
.
"STD -iMXB8440 -o\\OFCAPPSRVR\outputs\MXB8440.pdf"
)

foreach ($Command in $arrCommands)
{
$Return = ProcessCommands -ParamCommand $Command
$arrResults += New-Object Psobject -property @{COMMAND=$Command; EXITCODE=$Return.ExitCode; OUTPUT=$Return.StandardOutput}
}

----

problem with the powershell pipline parameter process

$
0
0

Hi,


I'm confused with the pipeline processing of object-property-parameter association.

Here my Cmdlet example

 

Function test-psboundbug{
	[CmdletBinding(DefaultParameterSetName='Parameter')]
 	param(
 	    [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)]
 	    [string]$Param1,
 	    [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)]
 	    [string]$Param2,
 	    [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)]
 	    [string]$Param3,
 	    [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)]
 	    [string]$Param4,
 	    [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)]
 	    [string]$Param5
    )    
    Begin{}
    Process{
        Write-Host " ====== BEGIN - PROGRESS =============="
        $PSBoundParameters
        Write-Host " ====== BEGIN - PROGRESS =============="
    }
    End{}
}
$testParams=@()
$testParams+=@{Param1="Param1-1";Param2="Param2-1"}
$testParams+=@{Param1="Param1-2";Param2="Param2-2";Param3="Param3-2"}
$testParams+=@{Param1="Param1-3";Param2="Param2-3";Param4="Param4-3"}
$testParams+=@{Param1="Param1-4";Param2="Param2-4"}
$testParams+=@{Param1="Param1-5";Param2="Param2-5"}
$testParams|%{New-Object psobject -Property $_}|test-psboundbug

when i send a array of objects through a pipline, i thoucht in every loop in the ''PROCESS''-Scriptblock the parameter accociation from the object properties is caculate exact on the behavior of the single object, which is active in processing.
But when the Property-Names are alterate in pipeline (see the example above), powershell is not resetting the $PSBoundParameters variable,but rather the $PSBoundParameters contains old values from the parent object in the pipeline loop, up to the end.

Here the Output of the example above:

 ====== BEGIN - PROGRESS ==============

Key                                     Value 
---                                     -----
Param1                                  Param1-1
Param2                                  Param2-1
 ====== BEGIN - PROGRESS ==============
 ====== BEGIN - PROGRESS ==============
Param1                                  Param1-2
Param2                                  Param2-2
Param3                                  Param3-2
 ====== BEGIN - PROGRESS ==============
 ====== BEGIN - PROGRESS ==============
Param1                                  Param1-3
Param2                                  Param2-3
Param3                                  Param3-2
Param4                                  Param4-3
 ====== BEGIN - PROGRESS ==============
 ====== BEGIN - PROGRESS ==============
Param1                                  Param1-4
Param2                                  Param2-4
Param3                                  Param3-2
Param4                                  Param4-3
 ====== BEGIN - PROGRESS ==============
 ====== BEGIN - PROGRESS ==============
Param1                                  Param1-5
Param2                                  Param2-5
Param3                                  Param3-2
Param4                                  Param4-3
 ====== BEGIN - PROGRESS ==============

The $PSBoundParameters contains the value of Param3 und Param4 up to end of whole process. I can manually Reset $PSBoundParameter.Clean() on the End of the PROCESS-Block and all worked as expected.

My Question is , is this a bug or a feature.

Jens Müller


create a child or subdomain in a field or domain in Windows Server 2008 R2 SP1 using Powershell

$
0
0

I am trying to create a child or subdomain in a field or domain in Windows Server 2008 R2 SP1 using Powershell.

ps>powershell.exe -noprofile -command "&{ start-process powershell -ArgumentList '-noprofile -file C:\Users\Administrator\Documents\Powershell\psfile.ps1' -verb RunAs}"

psfile.ps1

([WMIClass]"\\sandpit\root\MicrosoftDNS:MicrosoftDNS_Zone").CreateZone("subdomain.domain.com", 0, $False)

Fetch the data from sql server table to array

$
0
0

In the following script i am fetching the servers details from text file. Please anyone help me to get the same information from sql server database table. with using this query

"SELECT DISTINCT [server_name]FROMServers] whereStatus='1'"

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

$ServerName =Get-Content "c:\servers\servers.txt"

 foreach ($Server in $ServerName) {
     if (test-Connection -ComputerName $Server -Count 4 -Delay 2 -Quiet ) {
       write-output "$Server is alive and Pinging `n"

       } else {

      

Write-output "TXUE $Server seems dead not pinging"



I have to merge two csv files into 1 csv and then export out the related items in to csv files

$
0
0

I have 2 csv files that have data as per below that I want to import into excel using either PowerShell or a Visual Studio 13 code to merge the data from the imports into one excel sheet. or even to a SharePoint list.

CSV File 1 has

Period     Date

p1        2016-05-11

p2        2017-06-30

p3        2019-07-31

p4        2015-08-31

p5        2015-05-30

csv file 2 has

t

t1

t2

t3

t4

t5

and then I want the output to a workbook to be (merged)

period        Time           Date

p1               t1        2016-05-11

p2               t2        2017-06-30

p3               t3        2019-07-31

p4               t4        2015-08-31

p5               t5        2015-05-30

 Then all p1 item would need to be exported to their own csv file and then p2, p3 etc.. so on and so forth...

sample output:

Period       Time               Date

p1               t1        2016-05-11

p1               t1        2017-06-30

p1               t1        2019-07-31

p1               t1        2015-08-31

p1               t1        2015-05-30

Find a user in an array and output that line of the array

$
0
0

Hello

I have 2 arrays.

1 is Users (actually they are local admins on a server) aka $LocalAdmins
Jack
Joe
Jill

The other array contains 3 columns, one of which is usernames aka $NTResults
User              Last Write Time                          Last Access Time
James             1/1/2011 12:00:00am                  1/2/2011 12:01:00am
Joe                  2/3/2033 12:02am                           3/4/5030 9:01:am

I want take each user in the $LocalAdmins and search through the $NTResults array for that user. if i find that user, i need to retrieve that entire line, user, last write time, last access time. 

Ideas?

Thanks!

This is an example of the entire script. Will work on 2k8/7

$NTResults = @();
$ErrorActionPreference = "silentlycontinue"
$server = "LocalHost"

#------------------ Check for last logins ---------------#
$UserLookup = Get-ChildItem "\\$server\C$\users\*\ntuser.dat" -Force #| select @{e={(Split-path $_.Directory -Leaf)}},lastAccessTime,LastWriteTime | sort lastwritetime -Descending 

foreach ($User in $UserLookup)
{
$UserName = (split-path $User.Directory -leaf)

    #Populate Object
    $obj = @{
        User = $Username
        LastAccessTime = $User.LastAccessTime
        LastWriteTime = $User.LastWriteTime
        }
        $NTResults += New-Object psobject -Property $obj  
}
$NTResults | select user,LastWriteTime,LastAccessTime | sort LastWriteTime


#------------Lookup local admins---------------#  
$LocalAdmins = Gwmi win32_groupuser –computer $server
$LocalAdmins = $LocalAdmins |? {$_.groupcomponent –like '*"Administrators"'}  
$LocalAdmins = $LocalAdmins |% {  
$_.partcomponent –match “.+Domain\=(.+)\,Name\=(.+)$” > $nul  
$matches[1].trim('"') + “\” + $matches[2].trim('"')  }

#Trim DOMAIN\ from LocalUserAdmins
$LocalAdmins = $LocalAdmins -creplace '^[^\\]*\\', ''

#Arrys to populate and split users from groups
$LocalUsers = @()
$LocalGroups =@()

foreach ($LocalAdmin in $LocalAdmins)
    {
        if (dsquery user -samid $LocalAdmin)
        {$LocalUsers += $LocalAdmin}
        elseif (dsquery group -samid $LocalAdmin)
        {$LocalGroups += $LocalAdmin}
    }

Help Searching GPO XML

$
0
0

Good afternoon-

I'm trying to search all of the GPOs in my environment for "NT AUTHORITY\Authenticated Users" in any User Rights Assignment section. We need to implement a forest-wide authentication trust and need to know where "Authenticated Users" is used so that we can replace it with "Domain Users" and "Domain Computers." I have a Powershell script that is getting me close, but I can't seem to form the if() block in such a way that it actually works. This seems to be a good base:

[xml]$objGPO = Get-Content "PATHTOXMLFILEHERE"
Write-host $objGPO.GPO.Computer.ExtensionData.Extension.UserRightsAssignment.Member.Name -foregroundcolor green | Where { $_ -like "*NT AUTHORITY\Authenticated Users*"}

When I run this, I get:

       q1:Member                                     q1:Member

(in green) so I believe that it's finding a match. However, if I change the code to something like this:

[xml]$objGPO = Get-Content "PATHTOXMLFILE"
if($objGPO.GPO.Computer.ExtensionData.Extension.UserRightsAssignment.Member.Name | Where { $_ -like "*NT AUTHORITY\Authenticated Users*"}){
	Write-Host "Yes"
} else {
	Write-Host "No"
}

It always returns "No." I'm open to suggestions on other ways to accomplish what I'm looking for.

Thank you!!

Filter/ Variable Question

$
0
0

Why can I get results onscreen with this code:

## Generate List of all users in Password Change Lockout 
Write-Verbose "Generating List of users in Password Change Lockout Group" -Verbose
$PasswordChangeLockoutList = (Get-ADGroupMember -Identity "Password Change Lockout" -Recursive | Sort-Object | Select-Object -ExpandProperty SamAccountName )


## Filter out users with "Password Never Expires" and "User Must Change Password at next logon" checked
Write-Verbose 'Filtering users with "Password Never Expires" and "User Must Change Password at next logon" checked' -Verbose
Foreach ($name in $PasswordChangeLockoutList)
        {
        Get-ADUser -Identity $name -Properties * | Where-Object {$_.PasswordNeverExpires -eq $False -and $_.PasswordExpired -eq $False}|Sort-Object Name | Select-Object -ExpandProperty Name
        }

but when I insert a variable in the same code, I get nothing back?

## Generate List of all users in Password Change Lockout 
Write-Verbose "Generating List of users in Password Change Lockout Group" -Verbose
$PasswordChangeLockoutList = (Get-ADGroupMember -Identity "Password Change Lockout" -Recursive | Sort-Object | Select-Object -ExpandProperty SamAccountName )


## Filter out users with "Password Never Expires" and "User Must Change Password at next logon" checked
Write-Verbose 'Filtering users with "Password Never Expires" and "User Must Change Password at next logon" checked' -Verbose
Foreach ($name in $PasswordChangeLockoutList)
        {
        $Filtered = (Get-ADUser -Identity $name -Properties * | Where-Object {$_.PasswordNeverExpires -eq $False -and $_.PasswordExpired -eq $False}|Sort-Object Name | Select-Object -ExpandProperty Name)
        }

I get a list of names when I run the first script.  When I run the second one and type $Filtered, I get nothing.  

Please tell me I missing something simple.

Matt 


Matt Dillon



Exchange 2010 Picture Upload using Remote Powershell

$
0
0

When I first setup Exchange I cobbled together this Powershell command to upload pictures of the employees to display in outlook.  It runs fine when I am logged into the server and open the EMS, paste in and adjust the two paramters (user name, pic file name)

Import-RecipientDataProperty -Identity username -Picture -FileData ([Byte[]]$(Get-Content -path "\\scfiles\Outlook Pictures\user.name.jpg" -Encoding Byte -ReadCount 0))

Now I am looking for a way to remotely do this by right clicking the exchange server from my Server Manager on my Win 8.1 machine and choosing Windows PowerShell do this same script but always run into errors.

I've tried more things than I can relay in here. The last set of commands I thought I was getting closer but still not working.  Does anyone know how to achieve this, I am most certain it is possible to not have to RDP into one of my exchange server to just update/add a picture.

Last try I though would work :/

Viewing all 21975 articles
Browse latest View live


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