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

Execute PowerShell script on Many Machines

$
0
0

I have a power shell script that I can execute on a list of machines. The script will run the list of machines in parallel. 
The script appears to run fine.  But, let's say I have 500 machines to run my power shell script on.

I plan to have 10 lists that have 50 machines each.  10 power scripts.  Each power shell script uses a list
of 50 machines. So each script executes on 50 machines at a time.

Is there a better way to do this?  I am new to power shell


Query account privilegesprivileges for context running script

$
0
0

I am trying to enumerate the privileges for the account running a script to make sure it has Logon as Batch rights.

Anyone know how to do this?

Thanks!
jlc

Merge different CSV files into one CSV file in Powershell

$
0
0
Hi

I am using below script to export the permission from share folders.

=============
$a = (Get-Acl -Path '\\server1\depts')
$a.Access | Select-Object FileSystemRights, AccessControlType, IdentityReference, IsInherited | Export-Csv c:\deptsPermission.csv -NoTypeInformation

$a = (Get-Acl -Path '\\server2\Databases')
$a.Access | Select-Object FileSystemRights, AccessControlType, IdentityReference, IsInherited | Export-Csv c:\server2Permission.csv -NoTypeInformation

$a = (Get-Acl -Path '\\fileserver\Apps')
$a.Access | Select-Object FileSystemRights, AccessControlType, IdentityReference, IsInherited | Export-Csv c:\Apps.csv -NoTypeInformation

=============
The output files are generating seprately with name (deptspermission.csv, server2permission.csv and apps.csv)

Now I want all three csv file (deptspermission.csv, server2permission.csv and apps.csv) club in one CSV file, not in different different CSV file.

Now I am using below script to send mail for all three different CSV file.

# Email Variables
$emailsmtpServer = "smtp.mail.org"
$emailto = "myname@mail.org"
$emailfrom = "permission@mail.org"
$emailsubject = "permission"
$emailattachments = "c:\deptspermission.csv","c:\server2permission.csv","c:\apps.csv"
$emailbody = @"

Dear Team


"@

Send-MailMessage -To $emailto -From $emailfrom -Subject $emailsubject -Body $emailbody Attachments $emailattachments -SmtpServer $emailsmtpServer

So If I can get the all share folder permission in one CSV files then it would be great help for me

Working with Events Powershell

$
0
0

Hey guys,

So I'm trying to create an event registration from a WMI notifier query. What I would like to happen is for the wmi notifier to recognize a change in a specific service's state - then in action to this change - run a function I devised to simply turn the service back on. Now I know that the function works correctly and I know from wbemtest that toggling the service does create an event with my given query (I'm using the adobe updater service to test with on my machine). While I have this running in the console and the event registered- nothing ever happens when I disable the service - looks as if my function is never ran.

One thing I did notice was that my event notifier query returns this output "InstanceModificationEvent=<no key>" Whenever I toggle the service. 

Am I missing a step here? Do I need to do something more with the event notifier query??

I will paste my code below.

Function StartServ {
if ($global:WMIServiceObject.State -eq "Stopped"){
$global:WMIServiceObject.StartService() }
else {
break
}
}


$Global:WMIServiceObject = Get-WmiObject -Class Win32_Service | where {$_.Name -eq "AdobeARMService"}
$EventQuery = "Select * from __InstanceModificationEvent within 1 Where TargetInstance ISA 'Win32_Service' and TargetInstance.Name = 'AdobeARMservice'"
$Action = { StartServ }

Register-WmiEvent -Query $EventQuery -Action $Action 

My shell session (inside powergui) is running as admin so I don't believe that is the issue. Is there a way in my shell session to see if a notification is being recorded at all?

Thanks

Trouble installing SMTP on Server 2012 Standard Core

$
0
0

I asked this on the windows 2012 forum, where I was advised to ask this on this form.

I have a Server core instance I am administrating via PowerShell remoting. It has IIS and Sql 2008R2 functioning correctly and I want to add SMTP. I've verified its running 2012 standard edition:

PS C:\Users\JDearing\Documents> CimInstance Win32_OperatingSystem|select caption

caption
-------
Microsoft Windows Server 2012 Standard

I try to install SMTP with the following command: 

Add-WindowsFeature SMTP-Server,RSAT-SMTP -source:wim:d:\sources\install.wim:1 -Debug -Verbose

It fails with:

Add-WindowsFeature : The request to add or remove features on the specified server failed.
Installation of one or more roles, role services, or features failed.
The source files could not be downloaded.
Use the "source" option to specify the location of the files that are required to restore the feature. For more information on specifying a source location, see
http://go.microsoft.com/fwlink/?LinkId=243077. Error: 0x800f0906+ CategoryInfo          : InvalidOperation: (@{Vhd=; Credent...Name=localhost}:PSObject) [Install-WindowsFeature], Exception+ FullyQualifiedErrorId : DISMAPI_Error__Cbs_Download_Failure,Microsoft.Windows.ServerManager.Commands.AddWindowsFeatureCommand
DEBUG: Call to GetAlterationRequestState provider method failed with error(s): The request to add or remove features on the specified server failed.
Installation of one or more roles, role services, or features failed.
The source files could not be downloaded.
Use the "source" option to specify the location of the files that are required to restore the feature. For more information on specifying a source location, see
http://go.microsoft.com/fwlink/?LinkId=243077. Error: 0x800f0906

The ISO is mounted to the D: drive and the image for 2012 standard server cor is indeed 1:

 PS C:\Users\JDearing\Documents> Get-windowsimage –imagepath d:\sources\install.wim


Index       : 1
Name        : Windows Server 2012 SERVERSTANDARDCORE
Description : Windows Server 2012 SERVERSTANDARDCORE
Size        : 7,178,226,690 bytes

Index       : 2
Name        : Windows Server 2012 SERVERSTANDARD
Description : Windows Server 2012 SERVERSTANDARD
Size        : 11,999,889,351 bytes

Index       : 3
Name        : Windows Server 2012 SERVERDATACENTERCORE
Description : Windows Server 2012 SERVERDATACENTERCORE
Size        : 7,172,264,095 bytes

Index       : 4
Name        : Windows Server 2012 SERVERDATACENTER
Description : Windows Server 2012 SERVERDATACENTER
Size        : 11,995,265,169 bytes
What am I doing wrong?

Extract data from a .PST file via PowerShell

$
0
0

Hey guys,

I've inherited from the Symantec KVS vault administrator a .pst file with all my folders and documents.

I've mounted the file in Outlook and I can see all me folders and in each folder all my files.

I'm now looking for a way to automate th extraction of these files and folders on my local disk.

Would anyone know how I could process this 5Gb .pst file ?

Shall I start with Get-Content ? Will that cmdlet be able to reach the items and folders within the .pst

multi-threaded ping

$
0
0

I was given this script by a vendor to run on some of my servers.  I get some exceptions when I run it

Exception calling "Send" with "2" argument(s): "An exception occurred during a Ping request."
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : PingException
    + PSComputerName        : localhost

Can someone tell me how to write the below with Test-Connection instead of System.Net.NetworkInformation.Ping.  Here is the script

Function Test-Ping {
$parallelCount = $args[0] #Thread Count
$serverName  =$args[1]
$loop = $args[2]
$wait = $args[3]
$jobs = (1..$parallelCount) | % {start-job {
                $p = New-Object System.Net.NetworkInformation.Ping
                $serverName = $args[0]
                $wait = $args[2]
                (1..$args[1]) | % { $p.send($serverName, 10000); start-sleep -s $wait }
} -ArgumentList $serverName,$loop,$wait}
$jobs | wait-job
$jobs | receive-job
}

Test-Ping 24 myservername 10 1


Passing DateTime to Powershell Results in 00:00:00 Time

$
0
0

I have 2 basic powershell test scripts (test1.ps1 and test2.ps1)

Test1.ps1 looks like this:

$mytime =Get-DateWrite-Host"Passing in: $mytime"

$myvar =Invoke-Expression"C:\temp\Test2.ps1 -reftime $mytime"

Test2.ps1 looks like this:

param([datetime]$reftime)Write-Host"Received: $reftime"

When I run Test1.ps1, I receive the messages in the console pane:

Passing in: 06/17/2013 01:32:02
Received: 06/17/2013 00:00:00

Does anyone know why the time is changed to 00:00:00?

Thanks for any help.


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

Script to copy folders matching the name of folders in another directory, searching using a portion of the folder name e.g. first 4 characters.

$
0
0

Good afternoon guys,

I am totally new to PowerShell (only discovered it a week or so ago), or scripting in general for that matter, and therefore am finding it very difficult to tailor scripts I have found on the internet to fit my requirements.

If anyone could help me with this, I’d be extremely grateful;

I have two directories containing a lot of folders>subfolders>files. The first (search – called TEST A) directory is where the main body of files are kept – these are a mix of Excel and Email files which are put into folders named with a unique 4 digit number followed by some text e.g. “1000 – Folder123”.

The second directory (destination – called TEST B) contains an empty folders for each unique 4 digit number e.g. “1000”, “1001”, “1003”, “1004”, “1005” etc.

What I would like to do is run a script which looks up all of the folders in the search folder (TEST A) via the 4 digit number, matches it with the corresponding folder in the destination folder (TEST B), creates a new folder called “COPY TEST” in the matched folder in TEST B, and copies the TEST A folder  – along with any enclosed files – into this new folder called “COPY TEST”. As an example;

TEST A (FOLDER TO BE SEARCHED)                                      TEST B (FOLDERS FOR INFO TO BE COPIED INTO)         

E.g - C:\TEST A\1000 - Folder123                                           E.g - C:\TEST B\1000

"1000 - Folder123"                                                           "1000"

"1001 - Folder446"                                                           "1001"

"1002 - Folder789"                                                           "1002"

"1003 - Folder332"                                                           "1003"

Once the script had been successfully run, the updated TEST B folder would now look something like this:

"C:\TEST B\1000\COPY TEST\1000 - Folder123"

It would also be good if there was something in place to make sure no files were overwritten and that additional copies be made instead.

I hope my explanation is clear enough, although if anyone needs any further clarification I'll do my best to provide this.

Thank you all in advance for your help in this matter.

Regards,

Tom

Problem with looping...

$
0
0

Hi,

I'm in the process of writing a script which will update groups based on AD Attributes (department). This works great and reads a CSV with a list of groups and departments and adds uses to the relevant groups. The second section of the script reads the current group members and removes them if they are disabled - this part works too. But the part I am struggling on is where it reads the group members, checks if someone that is a member of the group shouldn't be anymore, by looking at their department. If there is only one member in the group it works fine, if there are more members in the group then it can't process them. I think it's because I need to loop it to check each user, but can't seem to get it to work.

I've commented the lines that are causing me the issue

#Script variables
#Make edits below this line

#Enter path to CSV file containing headers for ADDepartment,GroupName
$CSVFile = "c:\Source\Scripts\Depatmentalgroups\DepartmentalGroups-test.csv"
#Enter Log file path
$LogFile = "c:\Source\Scripts\Depatmentalgroups\logfile.txt"


#Don't change anything after this line
###############################################################################################################
#Get todays date
$today = Get-Date -DisplayHint Date

#Imports data from CSV file containing department names and group names - data is case sensistive
import-csv $csvFile | foreach {

#Adds users to group based on attributes
$dept = $_.DeptName
$ADGroup = $_.GroupName

$user = Get-QADUser -Department $dept -NotMemberOf $ADgroup -Enabled
If (!($user)) {Write-output  "$Today,$Dept,No-Matching-Users-Found" >> $LogFile}
	Else {Add-QADGroupMember $adgroup -member $user 
			Write-Output "$Today,$Dept,$user Was-Added-To-Group" >> $LogFile
			} 


#Removes any disabled users from group
$disableduser = Get-QADGroupMember $ADgroup -Disabled #check to see if users in group are disabled
If(!($disableduser)) {Write-Output "$Today,$Dept,No-Disabled-Users-To-Remove" >> $Logfile} #if no disabled users are found write it to logfile
	Else {Remove-QADGroupMember $ADGroup $disableduser  #if disabled users are found, remove them from the group
		Write-Output "$Today,$Dept,$disableduser,Was-Removed-From-Group" >>$logfile
		}

#Remove any user no longer in department
$groupmember = Get-QADGroupMember $ADGroup #gets all users left in group

If(!($groupmember)) {Write-Output "$Today,$Dept,Group-Was-Empty" >>$LogFile} #if no members are in the group write it to log file
	Else {$nolongermember = Get-QADUser $groupmember | Where-Object {$_.department -ne $dept} #otherwise get all users who are in the group but that don't match the required department
	#if more then one user is found in the above line, the get-qaduser fails with 'idenity' specified method is not supported - so i think i need to do something like foreach but struggling to figure this part out
	}

If(!($nolongermember)) {Write-Output "$Today,$Dept,No-Users-To-Remove" >> $LogFile}
	Else {Remove-QADGroupMember $ADGroup $nolongermember
		Write-Output "$Today,$Dept,$nolongermember,Was-Removed-From-Group" >>$logfile
		}
}

################################################################################################################


Regards,

Denis Cooper

MCITP EA - MCT

Help keep the forums tidy, if this has helped please mark it as an answer

My Blog

LinkedIn:

how to send multiple csv file to winzip as attachement

$
0
0

Hi

I have multiple csv file and I want to send all of them as attachment in zip format.

How can include all csv file in zip format.



Excluding from Convert to Html

$
0
0

Good afternoon,  I am using a powershell script to run a query on sql and grab the results and then save them to html.  The problem I am running into is that in addition to the fields I need it's adding hidden fields such as -  RowError, RowState, Table, ItemArray, HasErrors.  I want to only ConvertTo-HTML the two fields I need.  If I run the powershell with write host before its converted to html I get all the proper data but when it runs through the convert to html the hidden fields show up.  I just want to remove them but have yet to figure out how.  Code block below to give you a example.

##setup data source
$dataSource = "localhost"         	##SQL instance name
$database = "DBAMonitoring"   	  	##Database name
$sqlCommand = "exec usp_MyReport" 	##The T-SQL command to execute
$TableHeader = "My SQL Report"    	##The title of the HTML page
$OutputFile = "C:\MyReport.htm"   	##The file location

##set HTML formatting
$a = @"<style>
BODY{background-color:white;}
TABLE{border-width: 1px;
  border-style: solid;
  border-color: black;
  border-collapse: collapse;
}
TH{border-width: 1px;
  padding: 0px;
  border-style: solid;
  border-color: black;
  background-color:#C0C0C0
}
TD{border-width: 1px;
  padding: 0px;
  border-style: solid;
  border-color: black;
  background-color:white
}</style>"@

$body = @"<p style="font-size:25px;family:calibri;color:#ff9100">
$TableHeader</p>"@

##Create a string variable with all our connection details 
$connectionDetails = "Provider=sqloledb; " +"Data Source=$dataSource; " +"Initial Catalog=$database; " +"Integrated Security=SSPI;"
##Connect to the data source using the connection details and T-SQL command we provided above, and open the connection
$connection = New-Object System.Data.OleDb.OleDbConnection $connectionDetails
$command = New-Object System.Data.OleDb.OleDbCommand $sqlCommand,$connection
$connection.Open()
##Get the results of our command into a DataSet object, and close the connection
$dataAdapter = New-Object System.Data.OleDb.OleDbDataAdapter $command
$dataSet = New-Object System.Data.DataSet
$dataAdapter.Fill($dataSet)
$connection.Close()
##Return all of the rows and pipe it into the ConvertTo-HTML cmdlet, and then pipe that into our output file
$dataSet.Tables | Select-Object -Expand Rows |
ConvertTo-HTML -head $a –body $body |
Out-File $OutputFile






scripting in a trusted AD forests environment

$
0
0

Hello

I'm in charge of a complex operation of Exchange 2010 cross forest migration (users and mailboxes).
The process requires many steps in both forests such as:

1. Deleteing mail contact in target forest.
2. Disabling linked mailbox in source forest and enabling the user account
3. performing Prepare-MoveRequest.ps1 in source domain
4. Adding addresses
5. running the move request
and more....

I would like to automate the process as much as possible, and run it from a single server console (at the target forest).

The real question here is how can I perform remote powershell commands on both Exchange servers (Source server and Target server)
within the same script / commands.

How do I start a remote powershell session to the target Exchange server and source Exchange server and switch between both
in the same script back and forth ? and how do I terminate those sessions when I'm done ?

Thanks

2 arrays in a foreach

$
0
0

Hi

I have 2 arrays:

Array:  $allDB

NewContentDB_20130617_121431.BAK
SecureStoreDB_20130617_121431.BAK
sp2013DBconfig_20130617_121431.BAK
SP2013_State_Service_20130617_121431.BAK
SPenterpriseSearchDB_20130617_121431.BAK
SPprofileDB_20130617_121431.BAK
SPSearchServiceDB_20130617_121431.BAK
SPSearchServiceDB_AnalyticsReportingStore_20130617_121431.BAK
SPSearchServiceDB_CrawlStore_20130617_121431.BAK
SPSearchServiceDB_LinksStore_20130617_121431.BAK
SPsocialDB_20130617_121431.BAK
SPsyncDB_20130617_121431.BAK
SP_ContentDB_MySite_20130617_121431.BAK
SP_Content_CA_20130617_121431.BAK
SP_Metadata_Service_20130617_121431.BAK
webapp1ContentDB_20130617_121431.BAK
WSS_Content_20130617_121431.BAK
WSS_UsageApplication_20130617_121431.BAK

and

Array: $databasenames

NewContentDB
SecureStoreDB
sp2013DBconfig
SP2013StateService
SPenterpriseSearchDB
SPprofileDB
SPSearchServiceDB
SPSearchServiceDBAnalyticsReportingStore
SPSearchServiceDBCrawlStore
SPSearchServiceDBLinksStore
SPsocialDB
SPsyncDB
SPContentDBMySite
SPContentCA
SPMetadataService
webapp1ContentDB
WSSContent
WSSUsageApplication

So what i want to acheive is restoring my databases with..unfinished:

foreach ($DB in $databasenames)
{

RestoreDB $DB ('C:\SQLBackup\12 juni 2013\SQLbackup\' + $allDB[0])

}
The Problem is that I dont know how I can select both the first position of Arrays  $allDB and $databasenames in the "foreach" statement, so that through first run position of both arrays 1 ([0]) will be picked, then next time position 2,....etc

This is because $DB gives the database a name, while $Databasenames is the filename. So they have to fit:-)

Im quite stuck on this :\

any help will be greatly appriciated!

br

Bjorn



How to Loop Through Central Management Server in SQL Server 2012 Using PowerShell

$
0
0

I am trying to learn PowerShell.  I want to use it to gather information from a Central Management Server and input the information into a table in a database.

 


In Windows PowerShell ISE I am trying to run the following.  I am just running a test to see how it loops through the Central Management Server.  Maybe this example I found on http://sqlvariant.com/2011/01/powershell-week-at-sql-university-post-5/ isn't a good example?

---------------------
$filter = Set-AgentJobHistoryFilter -startDate $(get-date).AddDays(-3) -endDate $(get-date) -outcome 'Failed'

foreach ($RegisteredSQLs in dir -recurse SQLSERVER:\SQLRegistration\'Database Engine Server Group'\Test\ | where {$_.Mode -ne "d"} )
{
Get-AgentJobHistory $RegisteredSQLs.ServerName $filter | where-object {$_.StepID -ne 0}
}

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

 


I am getting the following error message:
---------------------
dir : SQL Server PowerShell provider error: Invalid Path: 'SQLSERVER:\SQLRegistration\Database Engine Server Group\Test'.
At line:3 char:29
+ foreach ($RegisteredSQLs in dir -recurse SQLSERVER:\SQLRegistration\'Database En ...
+                             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-ChildItem], GenericProviderException
    + FullyQualifiedErrorId : Microsoft.SqlServer.Management.PowerShell.GenericProviderException,Microsoft.PowerShell.Commands.GetChildItemCommand
---------------------

But I do not know how to fix it.  Can anyone explain to me why this isn't working?

 


lcerni

How to add Distribution Group email alias from CSV in office 365

$
0
0

Hello Forum!

 

Hope someone can help me troubleshoot this or even let me know if its not possible. But, I used powershell to import distribution groups and set primary emails in Office 365. That worked great, but we have two domains and i would like to add an email alias to all my DGs for the other domain.

 

This was my best attempt and its not going well:

 

Import-CSV "C:\distributionlists.csv" | foreach {Set-DistributionGroup "$_.Name" -EmailAddresses SMTP:$_.PrimarySmtpAddress,$SecondarySmtpAddress}

 

$_.Name is the column name for my DGs. IE: DL-IT

$_.PrimarySmtpAddress is the column name for my primary email. IE: IT@domain01.com

$_.SecondarySmtpAddress is the column name for my email alias. IE: IT@domain02.com

Create a SQL domain user with powershell

$
0
0

Hi

Is it possible to create a SQL login for an existing domain\user using powershell?

br

Bjorn

Local Administrators Group Listing

$
0
0

Thanks, Cyreli for giving me something to start with.  When I ran your code, I did not get any entries for the Administrators, which was all I needed.  A few tweaks & I got what I wanted.  (Very cool learning about how to tab the output). All I need to do is to read in a list of servers & I can produce a report for the corporate level.

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

$list =@() 
$server="SERVER1","SERVER2"
$server | % {
                $server = $_
                $server
$GMembers = $Null
$LocalGroup = [ADSI]"WinNT://$server.<domain>.com/Administrators,group"
$GMembers = $LocalGroup.psbase.invoke("Members") 
$GMembers | ForEach { $us = $_.GetType().InvokeMember("Adspath",'GetProperty', $null, $_, $null)
$us = $us -replace "WinNT://",""
$list += new-object psobject -property @{Server=$server}
                                                "`t $us"}
}

Help understanding strings in PS

$
0
0

Folks I'm new to PowerShell though I have done some programming in other langs.  Can someone help me understand the difference in the following:

1. 

$EmpID = "123456"

Get-ADUser -Filter "EmployeeID -eq $EmpID"

(No output - doesn't seem to work)

2. 

$test = "EmployeeID -eq '12346'"

Get-ADUser -Filter $test

(Get standard output seems to work fine.

I have a hard time understanding when I variable I have is a string, I'm guessing in one of the above it isn't a simple old generic string?  I tried teh following also:

Get-ADUser - Filter "EmployeeID -eq " + $EmpID

And it fails also.  Says it can't figure out how to add.. I sure miss the & type string concat from the old VBS days. . . 

Thanks for any help folks!!!

Viewing all 21975 articles
Browse latest View live


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