Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all 6937 articles
Browse latest View live

Powershell to append to an OOO that is already set

$
0
0

Hello,

I'm somewhat new to PowerShell.  I know how to Get and Set MailboxAutoReplyConfiguration.  What I need is a script that can Get the OOO and then Add additional text to it.  If one isn't set, then just add "I'm no longer working here"

I know it's along the lines of Get-MailboxAutoReplyConfiguration, If already set, then Export Username and OOO Message.  Else Set-MailboxAutoReplyConfiguration "I'm no longer working for XYZ Company"

I hope this makes sense.

Thanks in advance!


Updating Exchange Online (360 ) User properties from csv

$
0
0

Like  help with a script to update Exchange Online ( 360 ) User properties fields so when we open Outlook Contacts all fieilds are populated.

Thanks

 

Gary

 

Create Address List based on External Users

$
0
0

Hi, I am trying to create a script that will create an Address List based on all Users in an Organizational Unit. Each user is external to out organization - meaning they have a logon like user.name@ourdomain.com but have an email address but it is not at ourdomain.com.

I did find a way to create an Address List and have tried multiple different RecipientFilters. I have tried things like

Set-AddressList -Identity "\External Users" -RecipientFilter {$_.EmailAddress -notlike "*mydomain.com*"}< Not sure if this syntax is correct but you get the idea.

The latest attempt consisted of creating a distribution group and adding a single user to it. Then setting the address list with MemberOfGroup.

$group = $(get-distributionGroup ExternalDistribution).DistinguishedName
Set-AddressList -Identity "\External Users" -RecipientFilter "MemberOfGroup -like '$group'"

 

Any help is greatly appreciated,

 

Michael

 

Set-ADUser -replace question

$
0
0

Hello all,

I've been working on this for a good part of the day and I can't get it to work exactly as it is supposed to.  Perhaps I'm overlooking something.

Here is the scenario:

I am working on a new version of a user management script and I make use of one of the seldom used attributes (CarLicense) for holding information.

I was looking to keep a count of how many times a user is disabled by populating it with "DisableCount:#".

I get the current value using $prevdisablecount=(get-aduser SmithJA -property carlicense).carlicense -match "DisableCount"

This will give me a string like "DisableCount:1"

I can then say $updcount=($disablecount -split ":")[0]+1

$disablecount="DisableCount:$($updcount)"   - This should be something like "DisableCount:2".

Here is the problem:  When I use set-aduser -identity SmithJA -replace @{carlicense=$($prevdisablecount),$($disablecount)}, it adds the value instead of replacing.

It does the same whether I specify the variables in the set-aduser cmdlet either as $($__), "$___" or $___

It seems it's not able to translate the strings.    I can -remove and -add the same values, but I should be able to use -Replace.

How to get local printer

$
0
0

Hi, does  anyone  have a script that can get local printer on remote desktops and filter out OneNote and Document writer

 

Thanks in advance

'DependsOn' property ignored in custom resource

$
0
0

I have created a custom resource 'SyncShare' and I can get it to run with expected results if I copy the resource folder to the modulepath on the target node. However, if I try to combine copying that resource to the target and applying it in a single configuration ( see below), the LCM on the target says that the resource isn't in the psmodulepath –despite the fact that I have used the 'DependsOn' property to ensure that the directory exists. In fact, the custom resource is not respecting the dependsOn property at all, since I find that it is always being evaluated before the file resource that would make that resource available. See this configuration fragment:

File Resource_SyncShare
{
Type = "Directory"
DestinationPath = $Node.ResourceRootPath+"\SyncShare"
SourcePath = $Node.ResourceSourcePath+"\SyncShare"
Ensure = "Present"
MatchSource = $True
Recurse = $True
Force = $True
Credential = $Credential
Checksum = "modifiedDate"
}

SyncShare Tools
{
Name = "Tools"
SourceDirectory = $Node.ToolsDirSourcePath
DestinationDirectory = $Node.ToolsDirDestinationPath
ChecksumFileName = "sync.checksum"
Ensure = "Present"
DependsOn = "[File]Resource_SyncShare"
}

expoting hashtable to csv

$
0
0

Dear sirs

I'm building a powershell GUI application that has multyiple textboxes and comboboxes. I need to export the content of them to a csv, I created a hashtable and tried to export them to csv but it's not working

$props= {
        @{
            textboxotherin = $textboxin1.text
            textboxother1in = $textboxin2.text
            textboxinother1 = $textboxin3.text
            textboxinother2 = $textboxin4.text
            textboxinother3 = $textboxin5.text
            textboxhotherincombo = $comboboxin1.SelectedItem
            textboxother1incombo = $comboboxin2.SelectedItem
            textboxother4incombo = $comboboxin3.SelectedItem
            textboxother2incombo = $comboboxin4.SelectedItem
            textboxother3incombo = $comboboxin5.SelectedItem
                }
      
     $props| Export-Csv-Path($save.FileName + ".csv")-NoTypeInformation
}

any help will be appreciated

New-Mailbox / Set-CalendarProcessing / Set-Mailbox /Add-MailboxPermission --> for multiple users

$
0
0

Hey Guys,

time to admit defeat and post on the forum..

($RoomsAndMember.Users).Split(";")

seemed to work for all but the last command:

Add-MailboxPermission -Identity $RoomsAndMember.Alias -User ($RoomsAndMember.Users).Split(";") -AccessRights FullAccess

it gets the below error:

Cannot process argument transformation on parameter 'User'. Cannot convert the "System.Collections.ArrayList" value of type "System.Collections.ArrayList" to type
"Microsoft.Exchange.Configuration.Tasks.SecurityPrincipalIdParameter".
    + CategoryInfo          : InvalidData: (:) [Add-MailboxPermission], ParameterBindin...mationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Add-MailboxPermission
    + PSComputerName        : SERVERNAME

Ive done some googling and some people have mentioned Loops to fix this issue but I haven't figured out how to apply any of the scripts to my situation.

Full script below, I have copied other people scripts, haven't yet found a way to find the time to pick up a PS book and study the fundamentals:

$ExchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://SERVERNAME/powershell
Import-PSSession $ExchangeSession
Set-Location "C:\DATA\OneDrive\Work\Tech_Support\Scripts\Exchange - Create Exchange Room Add members"

$ExcelWB = new-object -comobject excel.application
    $Workbook = $ExcelWB.Workbooks.Open("C:\DATA\OneDrive\Work\Tech_Support\Scripts\Exchange - Create Exchange Room Add members\RoomsAndMembers.xlsx")
    $Workbook.SaveAs("C:\DATA\OneDrive\Work\Tech_Support\Scripts\Exchange - Create Exchange Room Add members\RoomsAndMembers.csv",6)
    $Workbook.Close($false)
    $ExcelWB.quit()
    $RoomsAndMembers = import-csv .\RoomsAndMembers.csv


ForEach ($RoomsAndMember in $RoomsAndMembers) {
    $RoomsAndMember
   New-Mailbox -Database "EXDB-06" -Name $RoomsAndMember.DisplayName -DisplayName $RoomsAndMember.DisplayName -UserPrincipalName $RoomsAndMember.UserPrincipalName -PrimarySmtpAddress $RoomsAndMember.PrimarySmtpAddress -Room -OrganizationalUnit "OU=Resource Mailboxes,OU=Production,DC=water,DC=internal" -Alias $RoomsAndMember.Alias -Office $RoomsAndMember.OfficeLocation
   Start-Sleep 15
   Set-CalendarProcessing -Identity $RoomsAndMember.Alias -ResourceDelegates ($RoomsAndMember.Users).Split(";") -BookInPolicy ($RoomsAndMember.Users).Split(";") -AutomateProcessing AutoAccept -MaximumDurationInMinutes "50400" -BookingWindowInDays "180" -DeleteSubject $false
   Start-Sleep 5
   Set-Mailbox -Identity $RoomsAndMember.Alias -GrantSendOnBehalfTo ($RoomsAndMember.Users).Split(";")
   Start-Sleep 5
   Add-MailboxPermission -Identity $RoomsAndMember.Alias -User ($RoomsAndMember.Users).Split(";") -AccessRights FullAccess
        }

 

Thank you very much in advance :) even pointing me to an explanation will suffice hopefully :)

 

 


Path with single quote and comma

$
0
0

Hi powerShell,

$fileList = dir 'H:\aa.txt','H:\bb.txt'
$newExtension = ".CSV"
$CsvFile = ""
$(foreach ($file in $fileList){
    $CsvFile = ((join-path $file.DirectoryName  $file.BaseName) + $newExtension)
    $CsvFile
})

the output:
H:\aa.CSV
H:\bb.CSV

I want to display output look like this as below:
'H:\aa.CSV','H:\bb.CSV'

how can i store the basename of an item of an array ( i need to cmpare it later) in powershell

$
0
0

$DirVan="C:\BestandVerplaatsen\van\*"

DirNa="C:\BestandVerplaatsen\naar"

#$File = Get-ChildItem C:\BestandVerplaatsen\van\*.* # HELP !! --> this is still an object wich contains an array

#I need an object wich contains an item of that array because i need to compare it later with an array i can't compare it

#or i don't know how . for example there is a file without an exention. first it should check if directory olso go a file with the same name but with the exentention .xml (based on basename). if it exesits it should copy both files to another direcotry. if it doesn't exist it shoulgive a warning

$File

 

 

=???

#HELP how to get an object wich contains one item of the array

echo

 

 

 

"print sfile"

$File

echo

 

 

""

#*******************************************************************

# Report baseName's

#*******************************************************************

#echo "basename wordt geplrint"

 

echo

 

 

 

 

"print basename of all files"

 

#get basename all files

 

$a

 

 

=gciC:\BestandVerplaatsen\van\*|% {$_.BaseName}

 

#$FilenameProper=$_.BaseName

$a

 

 

 

#echo whiteline

 

echo

 

 

""

 

#get basename xml files

 

echo

 

 

"print basename of .xml files" 

$b

 

 

=gciC:\BestandVerplaatsen\van\*-filter'*.xml'|% {$_.BaseName}

 $b

 

 

#*******************************************************************

# if files in directory copy to specific place

#*******************************************************************

foreach

 

 

($Filein$DirVan){

 

 

 

$exists=$DirVan|Where-Object {$_.BaseName -eq$_.BaseName}

# Help !!!

 

 

 

 

 

#what to fill in here because it needs to compare if there is a file in de directory with the same basename.

 

 

 

 

 

# if there is another file with the same basename it should execute some code below

 

 

 

 

if($exists

 

)

{

 

 

 

# execute code

}

}

 

 

Have lost command line

$
0
0
Hello,
I`am very new to powershell and im following a online crash course, so I can learn Python.

I was going really good for a beginner until I did this.

cd temp
new-item iamcool.txt -type file
ls
that worked fine and then I went to delete it but I didn't change one level up, now its saying

cmdlet remove-item at command pipeline position 1 supply values for the following parameters
path [0]

and I did a stupid thing now my screen looks like this


path[0] is
path[1] pwd
path[2] cd patrick
path [3] cd temp
path[4] help
path[5]

can you please help me restore my command line

Regards
Matthew

An operations error occurred,Microsoft.ActiveDirectory.Management.Commands.GetADGroupMember

$
0
0

I finally have some 2008 r2 servers that I get to use the Active Directory module cmdlets on.  Strange thing though,  when I run Get-ADGroupMember on the Administrator group, I get this error:

An operations error occurred,Microsoft.ActiveDirectory.Management.Commands.GetADGroupMember

I see a few other people say they have experienced this online, but no one gets to why.  Most of the time, the people responding try it and they don't have a problem.  It works fine with any other group, it just fails with the Administrator group. 

I can get what I need like this:

([ADSI]'LDAP://CN=Administrators,CN=Builtin,DC=Domain,DC=COM').member

but that doesn't really answer my question about what the problem is.

 

Active Directory Local Stack trace error

$
0
0

 

Hello,

The below issue is not happening all the time. Only on parallel execution of this command as xml from service now orchestrator. Even in parallel execution, only at times the error occurs.

We are facing local stack error when using the below commands. 

$Domains=Get-ADForest| select -ExpandProperty Domains;

 foreach($Domain in $Domains) {                        

              $User1=get-aduser $UserName -Server "$Domain";   

}

How to resolve ?

Error we got as below : A local error has occurredStack Trace: at Microsoft.ActiveDirectory.Management.AdwsConnection.ThrowExceptionForErrorCode(String message, String errorCode, String extendedErrorMessage, Exception innerException)at Microsoft.ActiveDirectory.Management.AdwsConnection.ThrowException(CustomActionFault caFault, FaultException faultException)at Microsoft.ActiveDirectory.Management.AdwsConnection.GetADForest(GetADForestRequest request)at Microsoft.ActiveDirectory.Management.ADWebServiceStoreAccess.Microsoft.ActiveDirectory.Management.IADTopologyManagement.GetADForest(ADSessionHandle handle, GetADForestRequest request)at Microsoft.ActiveDirectory.Management.ADTopologyManagement.GetForest()at Microsoft.ActiveDirectory.Management.Commands.ADForestFactory`1.GetExtendedObjectFromIdentity(T identityObj, String identityQueryPath, ICollection`1 propertiesToFetch, Boolean showDeleted)at Microsoft.ActiveDirectory.Management.Commands.ADGetCmdletBase`3.ProcessRecordOverride()at Microsoft.ActiveDirectory.Management.Commands.GetADForest.ProcessRecordOverride()at Microsoft.ActiveDirectory.Management.Commands.ADCmdletBase.ProcessRecord()

Exporting custom results to CSV

$
0
0

Good Morning Everyone,

I have a list of email addresses that I compare against our O365 tenant, if they exist I write-host telling me, if they do not exist I write-host telling me they do not.

What I would like to do is export the comparison to CSV file: in column A I would like the email address that was compared and in column B I would like to know whether the email address exists or not.

Would I need to create a custom ps object or hash-table? Confused

I have not really got much experience with creating custom output for a CSV file.

Thanks for any help you can provide.

Out-file issue

$
0
0

hello everyone,  I am having a little bit of a issue trying to get the out-file command to print to a text file on $dis = "2".  it still prints to the screen. any help is welcomed thank all

functionSkyzone1{

""

write-host"Script will retrieve the User system by whats in the description field in AD"-foregroundcolor"red"

""

$dis=Read-host'would you like to 1. display on screen 2. Write to cvs'

cls

if ($dis="1"){

 $d=Read-Host"Enter User name"

 ""

 $d=  "*$d*"

 Get-ADComputer-Filter {Description-Like$d} -SearchBase$skyzone-PropertiesDescription,name,LastLogonDate|select-objectName,Description,LastLogonDate

 Pause

 }

elseif($dis="2") {

 $dp=Read-Host"Enter User name"

 ""

 $dp=  "*$dp*"

 Get-ADComputer-Filter {Description-Like$dp} -SearchBase$skyzone-PropertiesDescription,name,LastLogonDate|Out-File-FilePathC:\Temp\results2.txt 

 

 }

Else{

write-host"Not a vaild option"

 }

 

 }

 


PSSession with Windows Update

$
0
0

This is the situation:

I work on a workstation (Windows 7) and want to perform an action on a server (Server 2008 R2).

The workstation is called MyWks01 and the server is called MyServer01.

Both machines are members of the same domain and I am logged on with domain admin credentials on the workstation.

UAC is disabled on the server.

I have a command prompt open as administrator and open a Powershell session.

 

The final aim is to perform Windows updates by executing a scriptblock remotely.

 

To test part of the solutiopn I perform following action:

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

RemoteServer = New-PSSession -ComputerName MyServer01

 

$Script = {

$session    = New-Object -ComObject Microsoft.Update.Session

$Downloader = $session.CreateUpdateDownLoader()

}

 

Invoke-Command -Session $RemoteServer -ScriptBlock $Script

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

This gives following error:

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

Exception calling "CreateUpdateDownloader" with "0" argument(s): "Access is

denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"

    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

    + FullyQualifiedErrorId : ComMethodTargetInvocation

    + PSComputerName        : MyServer01

 

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

If I replace $script with the following block:

$Script = {Get-ChildItem c:\Temp}

then everything works correctly (I get a list of files in the c:\Temp directory of the server)

 

Apparently it is the CreateUpdateDownloader() that poses a particuar problem, anyone any ideas?

 

BTW: CreateUpdateInstaller() has the same problem, on the other hand Windows.UpdateSearcher with the Search("IsAssigned=1" and IsInstalled=0) methods does work.

 

Problems running a command remotely with parameters

$
0
0

Hi

I am attempting to run a command with parameters remotely but have spent days trying to find the right format for the parameters. I have used PowerShell for a while but am new to remoting. The command that I am trying to execute is  MySQL.exe –uFred –ppassword  –e “create database IP_Addresslist”;  where –u is the user, -p is the password and –e specifies the mysql command to run (in quotes).

I have tried many combinations including the one shown below but with no success.

$MySQLuser="-uFred "

$MySQLPW="-ppassword "

$MySQLcmd="-e `"create database IP_Addresslist`";"

 

invoke-Command -ComputerName SERVER1 -ScriptBlock {"\\SERVER1\c$\Program Files\MySQL\MySQL Server 5.6\bin\mysql.exe " $using:MySQLuser,$using:MySQLPW,$using:MySQLcmd }

This particular command gives the following error message.

At E:\Programming\Powershell\Scripts\remote programming exercise.ps1:14 char:119

+ ... Files\MySQL\MySQL Server 5.6\bin\mysql.exe " $using:MySQLuser,$using: ...

+ ~~~~~~~~~~~~~~~~

Unexpected token '$using:MySQLuser' in expression or statement.

+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException

+ FullyQualifiedErrorId : UnexpectedToken

Does anybody have an idea of where I’m going wrong, or is there an easier way of achieving this? Thanks

 

 

combining variable + .pfx in foreach

$
0
0

Hi

I have a script that is supposed to copy a certificate for each server(certs are by name) and import it to each server and then set the rdp listener to use that certificate(instead of the default)

something like this:

$certsLocation="c:\temp"

 

 

 

 

 

 

 

 

$servernames

 

 

=Get-ChildItem$certsLocation|selectname|%{$_.name.Split("{.}") |select-First1}

ForEach

 

 

($serverin$servernames) {

if

 

 

(!(Test-Path\\$server\c$\certs)){New-Item-typedirectory-Path\\$server\c$\certs}

Copy-Item

 

 

-Path$certsLocation\$server.PFX-Destination\\$server\c$\certs-Force

$data

 

 

=Invoke-Command-ScriptBlock {Import-PfxCertificate–FilePathC:\certs\'$($server)+".PFX"'cert:\localMachine\my-Password (ConvertTo-SecureString-String"1234"-AsPlainText-Force)} -ComputerName$server

$thumbprint

 

 

=$data.Thumbprint

$path= (Get-WmiObject-computeradfs1-class"Win32_TSGeneralSetting"-Namespaceroot\cimv2\terminalservices-Filter"TerminalName='RDP-tcp'").__path

Set-WmiInstance

 

 

-Path$path-argument @{SSLCertificateSHA1Hash=$thumbprint

}

}

so far good

it seem to break here:

$data=Invoke-Command-ScriptBlock {Import-PfxCertificate–FilePathC:\certs\'$($server)+".PFX"'cert:\localMachine\my-Password (ConvertTo-SecureString-String"1234"-AsPlainText-Force)} -ComputerName$server

and specifically I think here:

C:\certs\'$($server)+".PFX"'

The system cannot find the path specified. 0x80070003 (WIN32: 3 ERROR_PATH_NOT_FOUND

now if I test this using the actual computer name it works no problem

for example:

=Invoke-Command-ScriptBlock {Import-PfxCertificate–FilePathC:\certs\server1.PFXcert:\localMachine\my-Password (ConvertTo-SecureString-String"1234"-AsPlainText-Force)} -ComputerName server1

so im guessing its either that combination with foreach loop or the name of the cert isn't being constructed right from comning server name and .PFX extension

anyway, any help would be appreciated

Thanks

 

 

Getting logged on users and print service status

$
0
0

 Hi ,

I am trying to add to my already existing code below, where I want to see who is logged on using this code here: Just having some trouble,  can anyone help?

gwmi -Class win32_process -Filter "name='explorer.exe'" | Foreach-Object { $_.GetOwner() } | select User.

__________________________________________________________________________________________

Existing script:

$Srvs = Get-Content 'serverlist.txt'

[string]$Body = Invoke-Command -ComputerName $Srvs -ScriptBlock { Get-Service Cpsvc | where-object { $_.status –eq "stopped"} } | select pscomputername | sort -Descending| ConvertTo-Html -Head $a

If ($Body -match "CTX"){
send-mailmessage -To "address" -from "address" -Subject "CTX print service stopped" -SMTPSERVER "IP" -Body $body -BodyAsHtml
}
Invoke-Command  -ComputerName $Srvs -ScriptBlock { Get-Service Cpsvc | where-object { $_.status –eq "stopped"} | start-Service }

Create a powershell script to launch multiple excel files.

$
0
0

Good Afternoon 

I have a user that would like to a powershell script so that we comes into the office in the morning he can just launch the powershell script and it will launch all his excel sheets for him, some of the excel sheets are located in different drives like H:\ and z:\

 

Ive never done this before and will like to know how to start with such a process 

 

If anyone can help it is greatly appreciated. 

 

Thank you 

Viewing all 6937 articles
Browse latest View live


Latest Images