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

Why cant I format a System DateTime correctly using custom formatting?

$
0
0

Hello,

When I execute a "ls c:\windows\LogFiles | gm", I see a Typename: System.IO.FileInfo with a Property of CreationTime which is a System.DateTime.  Im trying to format this System.DateTime by issuing a $DT = $_.CreationTime -f "MM_dd_yy HH_mm_ss", but what always comes back is a format of 06/17/2013 07:36:51.  Why is this?  How can I custom format this property to the form I need?


Thanks for your help! SdeDot


Help with setting folder permissions with Powershell

$
0
0

I can successfully create a new directory using Powershell, but I'm not quite clear on how to ADD a user and set their permissions to that directory.  The results I'm having is that the user is given permissions, but the previously set permissions disappear.

For example, I create a directory named JSMITH.  By default there are several groups and some users that have access to this directory.  After running my commands, only JSMITH and Administrator have permissions.  Really all I want to do is keep what's already there but just add this user and give them full permission.

New-item \\XXXVMFSR01\ARCHIVES\JSMITH -type directory
$acl = Get-Acl \\XXXVMFSR01\ARCHIVES\JSMITH
$acl | Format-List
$acl.GetAccessRules($true, $true, [System.Security.Principal.NTAccount])
$acl.SetAccessRuleProtection($True, $False)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("JSMITH","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
$acl.AddAccessRule($rule)
Set-Acl \\XXXVMFSR01\ARCHIVES\JSMITH $acl

Start-Process Question

$
0
0

Hello All,

Does anyone have any idea why the following will not uninstall a version of Java that's less than 7? I could've sworn I had this working a week ago..

Start-Process -Wait -FilePath "WMIC" -ArgumentList "product WHERE `"name LIKE '%Java(TM)%' and NOT version LIKE '7%'`" CALL uninstall"

Thanks!

Getting Outlook folder permissions for all Exchange users

$
0
0

I have a script that will pull permissions for all Exchange mailboxes for the calendar folder. This works quite well for just the calendar folders. However, I need to search all folders (not just default folders) for all mailboxes in my environment. I know it will be an intense script. Bottom line we are attempting to clean up our distribution lists that are set to security objects and need to know where someone has granted permissions to a security group.

FYI...I did search the archives for folder permissions and only got 10 hits. I am fairly new to PowerShell scripting so I apologize for my ignorance but would greatly appreciate any assistance you can provide.

# Get the mailboxes 
$Mailboxes = Get-Mailbox -Filter {RecipientTypeDetails -eq "UserMailbox"} -ResultSize unlimited
# An array for the output 
$Output = @()   
# Loop through the mailboxes 
ForEach ($Mailbox in $Mailboxes) {
  # Get the name of the calendar folder  
  $Calendar = (($Mailbox.PrimarySmtpAddress.ToString())+ ":\" + (Get-MailboxFolderStatistics -Identity $Mailbox.DistinguishedName -FolderScope Calendar | Select-Object -First 1).Name)    
  # Get the permissions on the folder  
  $Permissions = Get-MailboxFolderPermission -Identity $Calendar   
  # Loop through the permissions, populating the output array  
  ForEach ($Permission in $Permissions) {
  $Permission | Add-Member -MemberType NoteProperty -Name "Mailbox" -value $Mailbox.DisplayName   
  $Output = $Output + $Permission 
  } 
  }   
  # Write the output to a CSV file 
  $Output | Select-Object Mailbox, User, {$_.AccessRights}, IsValid | Export-Csv -Path e:\_logs\CalendarPermissions.csv -NoTypeInformation

Send-MailMessage script runs perfect on PSv3, but cannot authenticate user with PS v2

$
0
0

This drives me nuts: the code below runs perfectly in PowerShell Version 3. I can authenticate and send mail via live.com and googlemail.com. The password is "hardcoded" in the script, to avoid typos.

If I run it on the same PC (or any other) in PowerSehll v2, I get the following errors

(a) Live.com: Mailbox unavailable. The server response was: 5.7.3 Requested action aborted; user not authenticated (b) Gmail.com: Send-MailMessage : The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.

The script:

#requires -version 2.0"PSHost v" + (Get-Host).Version

$pwlive   = ConvertTo-SecureString 'PASSWORD' -as -f 
$userlive = 'johnsmith@live.com'
$smtplive = 'smtp.live.com'

$pwgmail   = ConvertTo-SecureString 'PASSWORD' -as -f 
$usergmail = 'johnsmith@googlemail.com'
$smtpgmail = 'smtp.googlemail.com'

$rcpt = 'annaexample@yahoo.com'
$text = "Testmail"

$credlive = new-object System.Management.Automation.PSCredential $userlive,$pwlive
$credgmail = new-object System.Management.Automation.PSCredential $usergmail,$pwgmail

# 1st try
"Send-MailMessage: Trying Live ..."
Send-MailMessage -SmtpServer $smtplive -UseSsl -to $rcpt -From $userlive -Subject "1st try: Powershellmail via Live.com, $(Get-Date -format hh.mm) Uhr" -Credential $credlive -Body $text -encoding ([System.Text.Encoding]::UTF8) 

# 2nd try
"Send-MailMessage: Trying Gmail .."
Send-MailMessage -SmtpServer $smtpgmail -UseSsl -to $rcpt -From $usergmail -Subject "2nd try: Powershellmail via Gmail.com, $(Get-Date -format hh.mm) Uhr" -Credential $credgmail -Body $text -encoding ([System.Text.Encoding]::UTF8) 

# 3rd try
"Net.Mail.SmtpClient: Trying Live ..."
$SMTPClient = New-Object Net.Mail.SmtpClient($Smtplive, 587) 
$SMTPClient.EnableSsl = $true 
$SMTPClient.Credentials = $credlive
$SMTPClient.Send($userlive, $rcpt, "3rd try: [Net.Mail.SmtpClient]-Mail via Live.com, $(Get-Date -format hh.mm) Uhr", $text)
# 4th try"Net.Mail.SmtpClient: Trying Gmail ..."
$SMTPClient = New-Object Net.Mail.SmtpClient($Smtpgmail, 587) 
$SMTPClient.EnableSsl = $true 
$SMTPClient.Credentials = $credgmail
$SMTPClient.Send($usergmail, $rcpt, "4th try: [Net.Mail.SmtpClient]-Mail via Live.com, $(Get-Date -format hh.mm) Uhr", $text)

Remote execution of a script

$
0
0

I'm trying to execute

Invoke-Command -ComputerName sp2010 -FilePath C:\temp\Sjov\GetListsItemsX.ps1

but it fails will kind of bogus errors, so I think I have totally misunderstood something here.

The same script executes fine by using "Enter-PSSession -ComputerName sp2010" and then executing the script.

My ps1 script starts with

Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue

----------------------ERROR OUTPUT FROM EXECUTING COMMAND---------------------------------------------

PS C:\Temp\Sjov> Invoke-Command -ComputerName sp2010 -FilePath C:\temp\Sjov\GetListsItemsX.ps1
Cannot find drive. A drive with the name '
# Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue
$viewFields = @"
    <ViewFields>
      <FieldRef Name='Created' />
      <FieldRef Name='Modified' />
      <FieldRef Name='FileLeafRef' />
      <FieldRef Name='ID' />
   </ViewFields>
"@
$filePath = ".\RigConfiguration.xml"
$fileOut = "test.txt"
$rigUrl = "http' does not exist.
    + CategoryInfo          : ObjectNotFound: (
# Add-PSSnapi...$rigUrl = "http:String) [Split-Path], DriveNotFoundException
    + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.SplitPathCommand

Thanks,

Jørgen


Jorgen

Problem using CSharpCodeProvider to add types at runtime

$
0
0

I am having an intermittent problem adding C# types from Powershell.  (If this isn't the right forum, please advise me on where to post my question).

I originally encountered this issue using the built-in Add-Type cmdlet, but in order to get at the root of the issue I have actually written my own variation of the cmdlet:

function New-Type {
  param(
    [Parameter(Mandatory=$True,Position=1)][string]$TypeDefinition=$(throw "Mandatory parameter -TypeDefinition missing.")
  )

  $Params = New-Object System.CodeDom.Compiler.CompilerParameters
  $Params.ReferencedAssemblies.AddRange($(@("System.dll", $([PSObject].Assembly.Location))))
  $Params.GenerateInMemory = $True
  $Temp = $(Get-Item ENV:TEMP).Value
  $Params.TempFiles = New-Object System.CodeDom.Compiler.TempFileCollection $Temp, $False

  $Provider = New-Object Microsoft.CSharp.CSharpCodeProvider
  Try {
    $CompilerResults = $Provider.CompileAssemblyFromSource($Params, $TypeDefinition)
    if ($CompilerResults.Errors.Count -gt 0) {
      $CodeLines = $TypeDefinition -Split '[\n]';
      $ErrorMessage = "Compilation Errors:"
      foreach ($CompileError in $CompilerResults.Errors) {
        $ErrorMessage = [String]::Concat($ErrorMessage, "`n", $CompileError.ToString())
      }
      Write-Error $ErrorMessage
    }
  } Catch [system.exception] {
    if ($_.GetType().ToString() -eq "System.Management.Automation.ErrorRecord") {
      Write-Error $_.Exception.ToString()
    } else {
      Write-Error $_.ToString()
    }
  }
}

This new function works great, but unfortunately it is no more reliable than Add-Type.  However I have been able to get a stack trace out of it:

System.IO.FileNotFoundException: Could not find file 'C:\Users\[name]\AppData\Local\Temp\abd4anxc.dll'.

File name: 'C:\Users\[name]\AppData\Local\Temp\abd4anxc.dll'

   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)

   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)

   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)

   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)

   at Microsoft.CSharp.CSharpCodeGenerator.FromFileBatch(CompilerParameters options, String[] fileNames)

   at Microsoft.CSharp.CSharpCodeGenerator.FromSourceBatch(CompilerParameters options, String[] sources)

   at Microsoft.CSharp.CSharpCodeGenerator.System.CodeDom.Compiler.ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters options, String[] sources)

   at System.CodeDom.Compiler.CodeDomProvider.CompileAssemblyFromSource(CompilerParameters options, String[] sources)

   at CompileAssemblyFromSource(Object , Object[] )

   at System.Management.Automation.DotNetAdapter.AuxiliaryMethodInvoke(Object target, Object[] arguments, MethodInformation methodInformation, Object[] originalArguments)

A few other folks seem to have observed similar issues before, but they were actually experiencing compiler errors.  I am not -- I appear to be running into an error wherein the compiler fails to serialize the assembly to a temp file (which is the little"trick" it performs to pretend that the compilation is happening in memory).

Unfortunately, this seems to be the worst kind of error, one that happens "sometimes" but not always.  I once actually put the code in a loop, and it failed 20k times in a row.  So when it's broken, it stays broken (for a little while anyway).  Sometimes re-starting Powershell will clear the problem, but not always.  So what's going on??

I would really like to avoid having to ship DLLs with my Powershell modules, so adding types dynamically is extremely appealing.  How can I determine what's causing this intermittent error?

Thanks!

Import Users via PowerShell to AD using CSV

$
0
0

Hi Guys,

I am trying to import users from a CSV into active directory. I have the following script but it doesn't do anything.

Import-CSV "C:\PowerShell\User\import\Intake2013.csv" | ForEach-Object {New-ADUser -Path 'OU=Intake2013,OU=Students,OU=Users,OU=ASH,OU=Establishments,DC=Ashdown,DC=INTERNAL' -Description $_.Description -AccountPassword (ConvertTo-SecureString $_.Password -AsPlainText -Force) -SamAccountName $_.sAMAccountName -GivenName $_.FirstName -Surname $_.LastName -DisplayName $_.DisplayName -Name $_.Name -OtherAttributes @{pager=$_.Pager} -UserPrincipalName $_.UPN -ProfilePath $_.ProfilePath -HomeDrive N: -HomeDirectory $_.HomeDir}
Import-CSV "C:\PowerShell\User\import\Intake2013.csv" | ForEach-Object {Add-ADGroupMember -identity 'CN=ASH Student Users,OU=Student Users,OU=User Groups,OU=Groups,OU=ASH,OU=Establishments,DC=Ashdown,DC=internal' $_.sAMAccountName}
Import-CSV "C:\PowerShell\User\import\Intake2013.csv" | ForEach-Object {Add-ADGroupMember -identity 'CN=ASH File Server 4,OU=General,OU=Groups,OU=ASH,OU=Establishments,DC=Ashdown,DC=INTERNAL' $_.sAMAccountName}

Does anyon ehave any idea what is going on?

Kind Regards

Tom Park


TPark IT Technician


Cannot index into a null array.

$
0
0

Hi

I am new to powershell, and as part of my code I have this;

New-SPProjectDatabase -Name $PWADB -ServiceApplication $projectserviceapp -Tag $tag

$WebAppURL = $WebAppURL
$web=Get-SPWeb $WebAppURL
$web.Properties["PWA_TAG"]=$tag
$web.Properties.Update()
Enable-SPFeature pwasite -URL $WebAppURL

(This is part of a script)

The second line seems to throw this error;

Cannot index into a null array.
At line:22 char:1
+ $web.Properties["PWA_TAG"]=$tag

Any ideas? It is driving me crazy as I don't know what it means - I cannot find anything on internet, that helps me

Querying WMI-object for Services - How to port check for WMI and handle exceptions?

$
0
0

Hi

I've enabled Active Directory Gateway Management Services on our 2003 domain I can now Powershell AD objects :-)

First task of the day.

Aim: determine which services on our servers are authenticating with the Domain Admin password. Yeah, some people have been naughty.

I'm a PS noob, but some time ago obtained a BSc in Computer Science, so can understand the principles of coding, but don't do much these days.  Thus far I've spent my first few proper hours this afternoon with PS and cobbled together the following

# Load the MS Active Directory cmdlets
 Import-Module activedirectory

# Get a list of computers in the two Servers OU (must sort that out)
Get-ADcomputer -LDAPFilter "(name=*)" -SearchScope Subtree -SearchBase "ou=servers,ou=gloucester,DC=domain,dc=co,dc=uk" | foreach-object {$_.Name} | Out-File c:\scripts\servers.txt
Get-ADcomputer -LDAPFilter "(name=*)" -SearchScope Subtree -SearchBase "ou=servers,ou=machines,ou=gloucester,DC=domain,dc=co,dc=uk" | foreach-object {$_.Name} | Out-File c:\scripts\servers.txt -Append

# If output file already exists then remove it
If (Test-Path -Path "C:\scripts\audit.txt") {Remove-Item "C:\scripts\audit.txt"}

$compArray = get-content C:\Scripts\Servers.txt
foreach($strComputer in $compArray)
{
write-output "Checking $strComputer for domain\Administrator" | Out-File "C:\scripts\audit.txt" -Append
Get-WMIObject Win32_Service -ComputerName $strComputer | Where-Object {$_.StartName -eq 'domain\Administrator'} | Format-List Name, StartName | Out-File "C:\scripts\audit.txt" -Append
write-output "Checking $strComputer for Administrator@domain.co.uk" | Out-File "C:\scripts\audit.txt" -Append
Get-WMIObject Win32_Service -ComputerName $strComputer | Where-Object {$_.StartName -eq 'Administrator@domain.co.uk'} | Format-List Name, StartName | Out-File "C:\scripts\audit.txt" -Append
}

That works for what can be contacted. However I need to handle this:

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x80070
BA)
t C:\scripts\wipservices.ps1:17 char:14
 Get-WMIObject <<<<  Win32_Service -ComputerName $strComputer | Where-Object {
_.StartName -eq 'Administrator@impello.co..uk'} | Format-List Name, StartName
 Out-File "C:\scripts\audit.txt" -Append
   + CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], COMExcept
  ion
   + FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands
  .GetWmiObjectCommand

I found this link which tantalisingly leads me to Test-Port. But by gad me head hurts now! :-)

Ideally, I need to port 135 test each server in the text file, perhaps strip out the failing to a log and only run a get-wmiobject against each verified server object?  I can't see how to return a false condition against Test-Port though.  Am I barking up the wrong tree?  Any worked solutions too would be very much appreciated. Need to learn and loving it so far :)  Good task to set myself, huh?

Problem using CSharpCodeProvider to add types at runtime

$
0
0

I am having an intermittent problem adding C# types from Powershell.  (If this isn't the right forum, please advise me on where to post my question).

I originally encountered this issue using the built-in Add-Type cmdlet, but in order to get at the root of the issue I have actually written my own variation of the cmdlet:

function New-Type {
  param(
    [Parameter(Mandatory=$True,Position=1)][string]$TypeDefinition=$(throw "Mandatory parameter -TypeDefinition missing.")
  )

  $Params = New-Object System.CodeDom.Compiler.CompilerParameters
  $Params.ReferencedAssemblies.AddRange($(@("System.dll", $([PSObject].Assembly.Location))))
  $Params.GenerateInMemory = $True
  $Temp = $(Get-Item ENV:TEMP).Value
  $Params.TempFiles = New-Object System.CodeDom.Compiler.TempFileCollection $Temp, $False

  $Provider = New-Object Microsoft.CSharp.CSharpCodeProvider
  Try {
    $CompilerResults = $Provider.CompileAssemblyFromSource($Params, $TypeDefinition)
    if ($CompilerResults.Errors.Count -gt 0) {
      $CodeLines = $TypeDefinition -Split '[\n]';
      $ErrorMessage = "Compilation Errors:"
      foreach ($CompileError in $CompilerResults.Errors) {
        $ErrorMessage = [String]::Concat($ErrorMessage, "`n", $CompileError.ToString())
      }
      Write-Error $ErrorMessage
    }
  } Catch [system.exception] {
    if ($_.GetType().ToString() -eq "System.Management.Automation.ErrorRecord") {
      Write-Error $_.Exception.ToString()
    } else {
      Write-Error $_.ToString()
    }
  }
}

This new function works great, but unfortunately it is no more reliable than Add-Type.  However I have been able to get a stack trace out of it:

System.IO.FileNotFoundException: Could not find file 'C:\Users\[name]\AppData\Local\Temp\abd4anxc.dll'.

File name: 'C:\Users\[name]\AppData\Local\Temp\abd4anxc.dll'

   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)

   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)

   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)

   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)

   at Microsoft.CSharp.CSharpCodeGenerator.FromFileBatch(CompilerParameters options, String[] fileNames)

   at Microsoft.CSharp.CSharpCodeGenerator.FromSourceBatch(CompilerParameters options, String[] sources)

   at Microsoft.CSharp.CSharpCodeGenerator.System.CodeDom.Compiler.ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters options, String[] sources)

   at System.CodeDom.Compiler.CodeDomProvider.CompileAssemblyFromSource(CompilerParameters options, String[] sources)

   at CompileAssemblyFromSource(Object , Object[] )

   at System.Management.Automation.DotNetAdapter.AuxiliaryMethodInvoke(Object target, Object[] arguments, MethodInformation methodInformation, Object[] originalArguments)

A few other folks seem to have observed similar issues before, but they were actually experiencing compiler errors.  I am not -- I appear to be running into an error wherein the compiler fails to serialize the assembly to a temp file (which is the little"trick" it performs to pretend that the compilation is happening in memory).

Unfortunately, this seems to be the worst kind of error, one that happens "sometimes" but not always.  I once actually put the code in a loop, and it failed 20k times in a row.  So when it's broken, it stays broken (for a little while anyway).  Sometimes re-starting Powershell will clear the problem, but not always.  So what's going on??

I would really like to avoid having to ship DLLs with my Powershell modules, so adding types dynamically is extremely appealing.  How can I determine what's causing this intermittent error?

Thanks!

Cannot index into a null array.

$
0
0

Hi

I am new to powershell, and as part of my code I have this;

New-SPProjectDatabase -Name $PWADB -ServiceApplication $projectserviceapp -Tag $tag

$WebAppURL = $WebAppURL
$web=Get-SPWeb $WebAppURL
$web.Properties["PWA_TAG"]=$tag
$web.Properties.Update()
Enable-SPFeature pwasite -URL $WebAppURL

(This is part of a script)

The second line seems to throw this error;

Cannot index into a null array.
At line:22 char:1
+ $web.Properties["PWA_TAG"]=$tag

Any ideas? It is driving me crazy as I don't know what it means - I cannot find anything on internet, that helps me

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

Set-ExecutionPolicy Unrestricted - Can I add this to my custom scripts?

$
0
0

As I learn an test PowerShell, I always run the command below so I can excute the ps1 script.
Set-ExecutionPolicy Unrestricted

I don't want to leave servers in this state.  Is there something I can put in my scripts that will allow me to run scripts, but not leave it in Unrestricted mode?

PowerShell - Setting targetAddress Active Directory attribute for all computers listed in CSV file

$
0
0

Hi,

I would like to add all the individual MAC addresses for each corresponding computer account in Active Directory through PowerShell. The list has already been created in a CSV file.

The column headers in the CSV file are as followed:

sAMAccountName,targetAddress

I checked the info in the CSV file list and the computer names and their corresponding mac addresses are on the same line seperated by a comma, so the CSV file is correct. There are over 100 computers in the list.

I want to write all the MAC addresses to the targetAddress attribute of each of their corresponding computer in AD, but my command is not working.

Here is my command:

Import-Csv c:\updateAD.csv | Set-ADcomputer -Identity { $_.sAMAccountName } -add @{targetAddress = $_.targetAddress}

Can someone help with the syntax, or perhaps I must use a different algorithm ?

Kind Regards,


Powershell and Zip Files

$
0
0

I want to be able to use Powershell to list the contents of a zip file as well as extract the files. Using Powershell v 3.0

I've been looking, but havn't found what I'm looking for yet.


Paul Arbogast

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

Autorun a script from Powershell Web Access

$
0
0

Hi Guys,

I am looking at building a powershell app within the Powershell web access tool.  I have got the Powershell web app working and am managing to populate the fields required (except for the user password) to make it easy for the users to log in (I have found that users generally don't follow instructions very well).

The only thing I need to do now is get a powershell script to run automatically when they successfully authenticate to the pswa.

Is there a setting somewhere where this can be done?  Users will get confused if they have to type in a command to run scripts.

Thanks

Glenn

create 2 dynamic file names based on file name read from folder

$
0
0

  I need to create 2 dynamic files based upon file name read and populate logs. This is what I tried but don't
know how to make file names created dynamic. There could be multiple files in root and I would like to keep output
in separate log files rather than accum into just one file. On the dynamic Fax log I don't want to log date and time just the data
from Write-Fax output below.


Function Write-Log($LogText){
$LogEntry=@"
$((Get-Date).ToString("dd-MM-yyyy HH:mm:ss")) > $($LogText)
"@
$LogEntry
$LogEntry | Add-Content 'c:\test\email.txt'     # I want this to be Shippernbr.txt
}


Function Write-Fax($LogText){
$LogEntry=@"
$((Get-Date).ToString("dd-MM-yyyy HH:mm:ss")) > $($LogText)
"@
$LogEntry
$LogEntry | Add-Content 'c:\test\fax.txt'        # I want this to be Shippernbr_Fax.txt
}


$rootfolder='C:\Test'

$files=Get-ChildItem "$rootfolder\*.csv"

ForEach($file in $files){
    Write-Log "Found file $file"
    Import-CSV $file -delimiter '|' | ForEach-Object{
        $attachment="$rootfolder\pdf\$($_.Shipper).pdf"
        Write-Log "Attachment is $($attachment)"
        Write-Fax "<adddoc:$attachment>"
        Write-Fax "<TOFAXNUM:$($_.FaxNbr)>"
        Write-Fax "<TONAME:$($_.Attn)>"
        Write-Fax "<TOCOMPANY: INV:$file>"
        Write-Fax "<FROMNAME: AUTO FAX>"
        $email=$_.Email
        Write-Log "Email address is $($email)"
        $emailCC=$_.EmailCC
        Write-Log "Email CC address is $($emailCC)"
       #Send-MailMessage -from "test-send@test.com" -To "test-send@test.com" -Subject 'Test Send' -SmtpServer 'local' -ErrorAction Continue
        if($?){
            Write-Log "Email Sent Successfully"
            Move-Item $file -Destination "$rootfolder\archive\" -WhatIf
            Write-Log "Moved file $($file) to $rootfolder\archive\"
            Move-Item $attachment -Destination "$rootfolder\archive\" -WhatIf
            Write-Log "Moved file $($attachment) to $rootfolder\archive\"
        }else{
            Write-Log "Email Send failed: $($error[0])";break
        }
    }
}





 Thanks.




















































































































SharePoint 2010 - PerformancePoint Dashboards - How to deploy them to a site collection using Powershell?

$
0
0

We developed number of dashboards using Dashboard Designer in SharePoint 2010. We are successfully able to deploy them using Dashboard designer. We have a requirement to migrate them from development box to other boxes (QA, UAT and Production) using Powershell script.

Can anyone help us on this?

Viewing all 21975 articles
Browse latest View live


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