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

Applying GPO to OWA feature when creating new mailboxes in Power Shell

$
0
0

Hello all,

I'm a super rookie with Power Shell and would appreciate a little assistance. I have a script that will create mailboxes from a CSV file and it works fine but there are a few things I don't know how to apply when creating the accounts.

1. Applying my GPO to OWA in Mailbox Features

2. Selecting the mailbox DB the user will be placed in.

This is what I have so far:

Import-Csv c:\Scripts\Myfile.csv | ForEach-Object {

 $password = ConvertTo-SecureString $_.Password -AsPlainText -Force
   
 New-Mailbox -Name $_.Name `
    -FirstName $_.FirstName `
    -LastName $_.LastName `
    -Alias $_.SamAccountName `
    -UserPrincipalName $_.UserPrincipalName `
    -Password $password `
    -ResetPasswordOnNextlogon $False `
    -OrganizationalUnit mydomain.com/Users

}

Any help would be appreciated. Thanks!


Select-String Pattern

$
0
0

Hello,

I have this script:

cls
$InetDrop = "c:\Temp"
$contains_stagingSP2010 = 	Get-childItem $InetDrop -filter *.eml -Recurse | `
							Select-String -Pattern ((' Staging *') -or (' SStaging *')) -AllMatches | `
							Select-Object Path,Filename
Write-Host $contains_stagingSP2010

In one of the files, there is the value Staging .Net included. but the result of my script is null.

How can i use -pattern with -or and -and ?


Thanks Horst MOSS 2007 Farm; MOSS 2010 Farm; TFS 2010; IIS 7.5

How to get powershell output on to a textfile ?

$
0
0
Now I want to get the whole powershell screen onto a text file without having to select all with the mouse which takes forever. Is there a command or one step easy process where i can output any power shell  command result or even the whole powershell screen on to a text file.

normal CSV file to a fixed record-size text file

$
0
0

Has anyone seen a utility written in PowerShell in a public repository that would take a CSV file and write out a fixed length record text file where each field of data in the CSV would occupy the same columns in each record of the text file?

I'm imagining a pre-pass to find the widths needed for each column and then a pass over the CSV file to write the fields right-justified in that width for each column.

For example,

image


Set registry rights and change Component Services with Powershell

$
0
0

Hello,

we must install a lot of SharePoint Server 2010. After the installation, we have to do every time the same thing.

Change the registry owner for the 2 key's: HKEY_CLASSES_ROOT\AppID\{61738644-F196-11D0-9953-00C04FD919C1} and HKEY_CLASSES_ROOT\AppID\{000.....}.

Change the permission for the admin group at this two key's to full.

After i have done this i must go to Win2008 Server -> Administrative Tools -> Component Services -> Computer -> MyComputer -> DCOM Config.

There i have to add users and change permissions at two application class properties -> Security Tab -> Lanch and activation permissions.

I would like to do this with powershell. I hope somebody can give me the instructions for this work.

Thanks Horst

 

 


Thanks Horst MOSS 2007 Farm, MOSS 2010 Farm, TFS 2008, TFS 2010

Splatting Query - Null Values

$
0
0

I'm looking for recommendations on the best way to deal with null values with splatting.

Take the example of updating title, department and telephonenumber on an aduser.

The following looks tidier, but will cause errors with null values (I don't want to see errors in the logs).

$splat=@{
  Title=$_.Title
  Department=$_.Department
  TelephoneNumber=$_.TelephoneNumber
}

Set-ADUser @Splat

Or one property at a time with IF statments

IF ($_.Title)
        {
        Set-ADUser $_.UserPrincipalName -Add @{Title=$_.Title}
        }

IF ($_.department)
        {
        Set-ADUser $_.UserPrincipalName -Add @{Department=$_.department}
        }

IF ($_.TelephoneNumber)
        {
        Set-ADUser $_.UserPrincipalName -Add @{TelephoneNumber=$_.TelephoneNumber}
        }

Any guidance on dealing with null values would be appreciated.

How would you code this.

I'm pretty new to Powershell, and I'm trying to get a handle on writing better code.  I can mostly achieve what I need now, but the code doesn't always look pretty.

how to run as admin powershell.ps1 file calling in batch file

$
0
0

I prepared one batch file .that file contains powershell file complete path to execute .

i want to execute this powershell file as run as administrator.

 

My batch file contains below text

powershell .\psfile.ps1

the above .bat file working fine on my dev box in which I'm having admin rights. But on some other env if i run the .ps1 file from power shell cmd prompt with administrator ,its working fine.


Srikanth Peddy. MCTS-BizTalk Server Please mark as answered .

Adding x500 addresses to multiple user objects using CSV input file

$
0
0

Hello

I need to add an x500 entry containing the legacy DN from our previous mail provider to the proxy address attribute for all our AD users.

I'm using a CSV file with the following format

user,legacy
rlanden,rlandenda3

I used the following powershell line to add the x500 entry:

Import-CSV d:\LegacyDN_input_list.csv | foreach{Set-ADuser -identity $_.user -add @{proxyAddresses = "X500:/o=mex05/ou=Exchange Administrative Group/cn=Recipients/cn=$_.legacy"}}

The X500 record was added to the objects but not as i wanted it, it turned out like this

/o=mex05/ou=Exchange Administrative Group/cn=Recipients/cn=@{user=rlanden; legacy=rlandenda3}.legacy

Could someone help explain why the output has ended up like this and how I can correct it.

Thanks,

Richard


get duration of a mp3 in seconds

$
0
0

how can I get the duration of a mp3 file in seconds ?

In need in seconds because  I use start-sleep and this cmdlet use -seconds parameter ..

I found a module that "read" the information about  files,  audio or video but it return in minutes  "00:03:51.6540000"

Can I convert  to seconds ? 

sorry for my english :D

Read the content of "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" (PowerShell v.2)

$
0
0

hi, I'm new in PowerShell but I want to learn about this language! have someone a idea about how can I Read the content of  'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run' ? I want to read the content and put in a variable and use for a checklistbox. I search on google, but I didn't find some usefull...

{

#OS : Windows XP SP 3 

#PowerShell V2

Powershell: Read-Host not working when ran from jump drive

$
0
0

I am writing a script that will get a data count off of HDDs that we work on.  Everything is working and when I added a Read-Host so that you could enter the drive letter of the connected HDD it worked until I put it on a jump drive and now all it reads is the jump drive drive letter.

RunMe.bat

@echo off
::  by: Joseph Monarch
pushd %~dp0
powershell -nologo -file "datacount.ps1"
pause

datacount.ps1

# User input for drive letter
$drive = Read-Host "Enter drive letter for data count. (ex. C)"

# Lists in an array all directories and files that need to be counted
$directory = get-childitem -Path "$drive:\*" -force -exclude *windows*, *Intel*, '*Program Files*', *.ini*, *Users*, *PerfLogs*, *eula*, *.dll*, *VC*, *.sys*, *Recycle*, '*Documents and Settings*', *ProgramData*, *Recovery*, '*System Volume Information*'
$directory += get-childitem -Path "$drive:\Users\*" -exclude '*All Users*', *Default*, '*Default User*', *AppData*, '*Application Data*', *Cookies*, *.dll*, *.ini*, *Microsoft*, *NetHood*, *PrintHood*, *Recent*, *SendTo*, '*Start Menu*', *Templates*, '*Saved Games*', *Searches* 
$directory += get-childitem -Path "$drive:\Program Files\*" -force -exclude '*Common Files*', '*Internet Explorer*', *MSBuild*, '*Reference Assemblies*', *Roxio*, *Symantec*, '*Uninstall Information*', '*Windows Defender*', '*Windows Journal*', '*Windows Mail*', '*Windows Media Player*', '*Windows NT*', '*Windows Photo Viewer*', '*Windows Portable Devices*', '*Windows Sidebar*', *.ini*
$directory += get-childitem -Path "$drive:\Program Files (x86)\*" -force -exclude '*Common Files*', '*Internet Explorer*', *MSBuild*, '*Reference Assemblies*', *Roxio*, *Symantec*, '*Uninstall Information*', '*Windows Defender*', '*Windows Journal*', '*Windows Mail*', '*Windows Media Player*', '*Windows NT*', '*Windows Photo Viewer*', '*Windows Portable Devices*', '*Windows Sidebar*', *.ini* , *Adobe*, *Bonjour*, *Google*, '*InstallShield Installation Information*', *Java*, *JRE*, *Microsoft.NET*, '*Mozilla Firefox*', '*Mozilla Maintenance Service*', *MSBuild*, '*MSXML 4.0*', '*OpenOffice.org 3*', *QuickTime*, *Temp*

#Get all profile names
$profile = get-item -Path $drive:\Users\* -exclude '*All Users*', *Default*, '*Default User*'
foreach ($name in $profile) {
    $name = $name.basename
    if($name -eq "Public") {""
    }
    else {
        # Search specific user folders
        if(Test-Path "$drive:\Users\$name\AppData\Local\Microsoft\Windows Mail") {
            $directory += get-item -Path "$drive:\Users\$name\AppData\Local\Microsoft\Windows Mail\*"
        }
        if(Test-Path "$drive:\Users\$name\AppData\Local\Microsoft\Outlook") {
            $directory += get-item -Path "$drive:\Users\$name\AppData\Local\Microsoft\Outlook\*"
        }
        if(Test-Path "$drive:\Users\$name\AppData\Local\Microsoft\Windows Live Mail") {
            $directory += get-item -Path "$drive:\Users\$name\AppData\Local\Microsoft\Windows Live Mail\*"
        }    
    }
}
# Get total size for each item in $directory in KB
$count = foreach ($dir in $directory) {
    $size = Get-ChildItem $dir -recurse -force -ErrorAction SilentlyContinue | Measure-Object -Sum Length
    $dsize = $size.sum / 1KB
    $tsize = "{0:N2}" -f $dsize
    $tsize
}

# Sum all the items in $count
function Get-Sum ($count) {
    return ($count | Measure-Object -Sum).Sum
}

$scount = Get-Sum($count)

#Display results in MB
if ($scount -le 1MB) {
    $tcount = $scount / 1KB
    $tcount = "{0:N2}" -f $tcount
    Write-Host "$tcount MB"
}
#Display results in GB
elseif ($scount -le 1GB) {
    $tcount = $scount / 1MB
    $tcount = "{0:N2}" -f $tcount
    Write-Host "$tcount GB"
}
#Display results in TB
elseif ($scount -le 1TB) {
    $tcount = $scount / 1GB

Also I get this error in regards to this line of code

Measure-Object : Property "Length" cannot be found in any object(s) input.
At C:\Users\Owner\Documents\datacount.ps1:49 char:94+     $size = Get-ChildItem $dir -recurse -force -ErrorAction SilentlyContinue | Measure-Object <<<<  -Sum 
Length+ CategoryInfo          : InvalidArgument: (:) [Measure-Object], PSArgumentException+ FullyQualifiedErrorId : GenericMeasurePropertyNotFound,Microsoft.PowerShell.Commands.MeasureObjectCo 
   mmand
Measure-Object : Property "Length" cannot be found in any object(s) input.
At C:\Users\Owner\Documents\datacount.ps1:49 char:94+     $size = Get-ChildItem $dir -recurse -force -ErrorAction SilentlyContinue | Measure-Object <<<<  -Sum 
Length+ CategoryInfo          : InvalidArgument: (:) [Measure-Object], PSArgumentException+ FullyQualifiedErrorId : GenericMeasurePropertyNotFound,Microsoft.PowerShell.Commands.MeasureObjectCo 
   mmand

if(Test-Path "$drive:\Users\$name\AppData\Local\Microsoft\Windows Live Mail") {
            $directory += get-item -Path "$drive:\Users\$name\AppData\Local\Microsoft\Windows Live Mail\*"
        } 


How to filter on * without using wildcard

$
0
0
Hi

I hope you can help.

I have to Get-ADUser -filter where displayname MUST contain a star 

It seems that PowerShell thinks I am using wildcard - I am not - I want to list users with a star * in their name :-)

What to do?

BR
Steen

"Select" Problem with leading underscore

$
0
0

In my script I am trying to use "Select" on _Server, DisplayName and Version.  Unfortunately it displays everything except  _Server in my csv file. How do I fix this?

My script:

Get-WmiObject -Class Win32Reg_AddRemovePrograms  -computer $computers | Select _Server, DisplayName, Version |Export-CSV c:\results\1172_ClassRoom_InventoryRaw.csv -notypeinformation

Copy-item script ... this is blowing my mind

$
0
0

all I want to do is take a folder and ALL folders and files within & copy them to a block of servers, but the following fails:

$Servers = import-csv -path "c:\WebServ.csv"
$path1 = get-item -path "$env:systemdrive\Microsoft SQL Server JDBC Driver 3.0"
$path2 = "$server\c$\Program Files\"
Start-Transcript -path "C:\Filecopy.log" -append
foreach ($server in $servers)
	{	
		copy-item -path "$path1" -destination "$path2"
	}
Stop-Transcript

The csv file has 1 column with a header, that header being "ServerName"

I don't understand the error I get:

copy-item : Item with specified name C:\c$\Program Files\Microsoft SQL Server JDBC Driver 3.0 already exists.

The folder doesn't exist at the destination.

and ...

what's the deal with the C drive being referenced twice?

I'm ready to tear my hair out :-(


Download webpage using powershell

$
0
0

I'm using the following code to try to download a webpage in powershell:

$web = New-Object Net.WebClient
$web.DownloadString("http://fqdn/rs_server.dll")

But it just returns to a PS> prompt.  No errors or anything.  If I enter an invalid address, I get an error.  If I enter another site, such as bing.com, it pulls back the data.  Any thoughts?

When I go to http://fqdn/rs_server.dll in IE, the page displays as expected.


Calendar permissions for all in Office 365 using PowerShell

$
0
0

Hello all,

In office 365, what I am trying to achieve is to give everyone , everyone's full access to calendar permission.

Meaning, If I have 10 users in O365, every one  must have everyone's calendar access to add, deleted, edit the calendar/meeting entries.

Can this be achieved by PowerShell ?

Email function + Monitor Serial Numbers

$
0
0

Hello,

I am a newbie Powershell scripter, but have put together something that is mostly functional. The problem I have is that I have the information I need but once that info is put into a variable to be sent through email, it doesn't seem to transfer the information..

Below is the code, and the email shows up blank. I have hard set the $msg.body to something and it does email the string properly. So from what I can tell the $msg.body has issues with something included in the returned variable but I cannot tell.

Thanks in advance, and maybe this code will help someone else.

(I have put the smtp server as X.X.X.X but in my version it has the proper IP address as well as the email addresses)

#Get-MonitorInfo

Function Get-MonitorInfo
{
    [CmdletBinding()]
    Param
    (
        [Parameter(
        Position=0,
        ValueFromPipeLine=$true,
        ValueFromPipeLineByPropertyName=$true)]
        [alias("CN","MachineName","Name","Computer")]
        [string[]]$ComputerName = $ENV:ComputerName
    )
 
    Begin {
        $pipelineInput = -not $PSBoundParameters.ContainsKey('ComputerName')
    }
 
    Process
    {
        Function DoWork([string]$ComputerName) {
            $ActiveMonitors = Get-WmiObject -Namespace root\wmi -Class wmiMonitorID -ComputerName $ComputerName
            $monitorInfo = @()
 
            foreach ($monitor in $ActiveMonitors)
            {
                $mon = $null
 
                $mon = New-Object PSObject -Property @{
                #ManufacturerName=($monitor.ManufacturerName | % {[char]$_}) -join ''
                ManufacturerName=($monitor.ManufacturerName | % {[char]$_}) -join ''
                ProductCodeID=($monitor.ProductCodeID | % {[char]$_}) -join ''
                SerialNumberID=($monitor.SerialNumberID | % {[char]$_}) -join ''
                UserFriendlyName=($monitor.UserFriendlyName | % {[char]$_}) -join ''
                ComputerName=$ComputerName
                WeekOfManufacture=$monitor.WeekOfManufacture
                YearOfManufacture=$monitor.YearOfManufacture}
 
                $monitorInfo += $mon
            }
            #Write-Output $monitorInfo
            $monitorInfostring = $monitorInfo.toString()
            return $monitorInfo
        }
 
        if ($pipelineInput) {
            DoWork($ComputerName)
        } else {
            foreach ($item in $ComputerName) {
                DoWork($item)
            }
        }
        
    }
    
}
 function sendMail{
     #Write-Host "Sending Email"
     #SMTP server name
     $smtpServer = "X.X.X.X"
     #Creating a Mail object
     $msg = new-object Net.Mail.MailMessage
     #Creating SMTP server object
     $smtp = new-object Net.Mail.SmtpClient($smtpServer)
    
     #Email structure
     $msg.From = "test@test.org"
     $msg.ReplyTo = "test@test.org"
     $msg.To.Add("test@test.org")
     $msg.subject = "My Subject"
     
     $BodyInfo = Get-MonitorInfo
 
     $msg.body = $BodyInfo    
     write-output $BodyInfo
          
    
     #Sending email
     $smtp.Send($msg)
 
}
#Calling function
sendMail
 

not finding RDSConfiguration in Remote desktop services

$
0
0

when i go to cd RDS: and do DIR i see only LicenseServer not RDSConfiguration because of which i am not able to go to RDSConfiguration and change the session limits. Please refer the image for more details, here i am able to change the sessionlimit for "DEN-GW-01", "DEN-SRV-01","DEN-SRV-02". The link to access the microsoft lab is

https://cmg.vlabcenter.com/lab/4fde280e-46b1-4256-a27b-e032e01d79a2

please help.

  


powershell script import exchange contacts from a csv file (advanced version)

$
0
0

Hi all. I'm tryng to create a scheduled task that runs daily, where it will create new users, update (modify) exisiting users and delete users based on a comparison between users in a csv file and exchange contacts.

I set up a test environsment purely consisting of a basic Windows Server 2008 R2 domain controller and an Exchange 2010 SP1 server.

I run this powershell script from the Exchange server as a domain admin.

I can see the script correctly gets values from the csv file from the Host-Write command with the various variables. However it seems like line 77 to 83 doesn't work, where it tries to create a New-MailContact. I can't see the contact in either Exchange or the AD and when the script tries to run Set-Contact to further modify the contact from line 86 it states the operation couldn't be performed because object 'user e-mail address' couldn't be found on 'DomainController.domain.local'.

Please note that I've used this site for inspiration: [Link removed due to: Body text cannot contain images or links until we are able to verify your account]

Please can anyone tell me why the script is failing to create the exchange contact? Here's an anonymized version of the script:

# Enable Exchange Shell Commands
 Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010

# Set the file location
 $rawfile = “.\contacts.csv”
 
# Ignore Error Messages and continue on. Comment this out with a # symbol if you need verbose errors
# trap [Microsoft.Exchange.Configuration.Tasks.ManagementObjectNotFoundException] { continue; }
 
$contactfile = Import-CSV $rawfile -delimiter ";"

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

# Read contacts and make the magic happen
 ForEach ($contact in $contactfile) {
 
# Read all attributes provided by the file
 $sourceEmail=$contact.mail_xml
 $sourceFirstName=$contact.givenName_xml -replace ” “,”-”
 $sourceLastName=$contact.sn_xml -replace ” “,”-”
 $sourceBranchCode=$contact.department_xml
 $sourceBranchLegalName=$contact.company_xml
 $sourcePhoneNumber=$contact.telephoneNumber_xml
 $company=$contact.company_xml
 $targetFirstName = $sourceFirstName
 
 
# Assign the Display Name using the correct First Name, Last Name and a suffix of COMPANY. We trim this field because of leading spaces that show up regularly
 $sourceDisplayName = “$targetFirstName $sourceLastName $company”
 $targetDisplayName = $sourceDisplayName.Trim()
 
# Assign the Distinguished Name attribute using the correct First Name, Last Name and OU structure
 $targetDistinguishedName = “CN=$targetFirstName $sourceLastName,OU=ExternalContacts,DC=domain,DC=local”
 
# Assign the name attribute for new contacts
 $targetCommonName = “$sourceFirstName $sourceLastName”
 
# Assign the Alias using COMPANY as a prefix so that we can identify them easily

$targetAlias = “$company $targetFirstName $sourceLastName”

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

###################################################
# Search for the contact to see if it is existing #
###################################################
 
if (Get-Contact -Identity $sourceEmail)
 {
 # Output to screen so we can track the process. Comment the following line when it is running as a batch process
 Write-Host $sourceEmail Exists so $targetDisplayName will be MODIFIED -foregroundcolor green
 
Set-MailContact -Identity $sourceEmail -Alias $targetAlias -ForceUpgrade
 Set-Contact -Identity $sourceEmail `
 -Company $sourceBranchLegalName `
 -Department $sourceBranchCode `
 -DisplayName $targetDisplayName `
 -SimpleDisplayName $targetDisplayName `
 -Name “$targetCommonName” `
 -FirstName $targetFirstName `
 -LastName $sourceLastName `
 -Phone $targetPhoneNumber `
 -WindowsEmailAddress $sourceEmail -WhatIf
 }

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

###################################################
 # If it is not existing, create a new contact     #
 ###################################################
 else
 {
 # Output to screen so we can track the process. Comment the following line when it is running as a batch process
 Write-Host $sourceEmail Does Not Exist so $targetDisplayName will be CREATED -foregroundcolor yellow
 
# First we create the contact with the required properties
 New-MailContact -ExternalEmailAddress "$sourceEmail" `
 -Name "$targetCommonName" `
 -OrganizationalUnit “OU=ExternalContacts,DC=domain,DC=local” `
 -DisplayName $targetDisplayName `
 -FirstName $targetFirstName `
 -LastName $sourceLastName `
 -PrimarySmtpAddress $sourceEmail -WhatIf
 
# Now we set the additional properties that aren’t accessible by the New-MailContact cmdlet
 Set-Contact -Identity $sourceEmail `
 -Company $sourceBranchLegalName `
 -Department $sourceBranchCode `
 -DisplayName $targetDisplayName `
 -SimpleDisplayName $targetDisplayName `
 -FirstName $targetFirstName `
 -LastName $sourceLastName `
 -Phone $targetPhoneNumber `
 -WindowsEmailAddress $sourceEmail -WhatIf
 }
 
# Clean up after your pet – this does some memory cleanup
 [System.GC]::Collect()
 [System.GC]::WaitForPendingFinalizers()
 }

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

##################################################################
 # Now we reverse the process and remove contacts no longer valid #
 # If contact is not in the file, delete it                       #
 ##################################################################
 
$CurrentContacts = Get-MailContact -OrganizationalUnit ‘OU=ExternalContacts,DC=domain,DC=local’ -ResultSize Unlimited | Select-Object PrimarySMTPAddress,name
 ForEach ($contact in $currentContacts) {
 $sourceEmail = $Contact.PrimarySMTPAddress
 if ( Get-Content $rawFile | Select-String -pattern $sourceEmail )
 {
 # Output to screen so we can track the process. Comment the following line when it is running as a batch process
 Write-Host This contact $sourceEmail Exists in the file -foregroundcolor green
 }
 else
 {
 # Output to screen so we can track the process. Comment the following line when it is running as a batch process
 Write-Host “DELETE THIS CONTACT $sourceEmail” -backgroundcolor yellow
 Remove-MailContact -Identity “$sourceEmail” -Confirm:$Y -WhatIf
 }
 }
 
$CurrentContacts = $null
 # Clean up after your pet – this does some memory cleanup
 [System.GC]::Collect()
 [System.GC]::WaitForPendingFinalizers()

New-SPConfigurationDatabase : Microsoft SharePoint is not supported with version 4.0.30319.18034 of the Microsoft .Net Runtime.

$
0
0
I'm using the AutoSPInstaller from codeplex and now recieve this error. Is this a problem of my server or is it something I defined wrong in the configDB?

The following is my signature:

Powershell Programmer & Advanced Lua Programmer

Location: Switzerland

Beside that, whenever you see a reply, you think is helpful, click "Vote As Helpful"! And whenever you see a reply being an answer to the main question of the thread, click "Mark As Answer" (if you opened the thread).

I published the URL's for the icons in my signature.

Please contact me, before reporting me, thank you.

[string](0..21|%{[char][int]([int]("{0:d}" -f 0x28)+('577076797174-87661607769657424-8687168065964').substring(($_*2),2))})-replace' '

Viewing all 21975 articles
Browse latest View live


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