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

foreach start loop at index[1]

$
0
0

I am importing a csv file into a variable then I am enumerating each element using a foreach loop, however my question
is how can I start my enumeration at index[1]?


code:

$Info = Import-Csv  'C:\Scripts\Description.csv' -Header computer, propertytag 


foreach ($info1 in $info){

 $computername = $info1.computer


}

reuslts: my result includes the header name computer which is index[0], which I don't want

computer                                                                                                                                                                                                          
--------                                                                                                                                                                                                  
computer                                                                                                                                                                                                             
3417EB9E27D0


Reg:: Need to Change Office-365 users Display name as FirstName+Lastname

$
0
0

Hi PowerShell Experts,

Greetings!!

We are having around 18k student accounts in Office-365 tenant. As of now the student display name is student id (Ex: u999998). If students sent email to respective lecturers or professors, they will receive an email from students with student-id as display name. Hence professors are unable to identify the student name.

Now, Professors would like to change the display name as Student Name(First Name + Last name). Ex: Madhu Vana.

I know the process of changing display name for single user. But, we need to change the display name for around 18k users at once.

For Single user, i can change the display name with the followed snippet,

Set-Mailbox u999998@domain.com -DisplayName Madhu_Vana.

We needed PS script for multiple users, Please help me to do the requested change successfully.

Many Thanks,

Madhu Vana

How to use -notlike with 2 values concatened

$
0
0

I am trying to validate users home folder that it is a specific share with the foldername as the id of the user

I already have tried a lot, but all give syntax errors

Basically I would like something like this:

Get-ADUser -Filter { (homedirectory -notlike "\5c\5cserver\5cuser_Home\5c" + SamAccountName ) }
or

Get-ADUser -Filter * -Properties HomeDirectory | where {$_.HomeDirectory -notlike concat("\\server\user_Home\",SamAccountName)}

Office 365 License Inventory

$
0
0

I'm trying to pull Office 365 licenses into Excel.

This code is run from the "Windows Azure Active Directory Module for Windows PowerShell" and requires installation of "Microsoft Online Services Sign-In Assistant for IT Professionals"  see below links for more info:

azure.microsoft.com/en-us/documentation/articles/powershell-install-configure/

Microsoft.com/en-us/download/details.aspx?id=28177

My questions is this:

1. How can I construct the script so I don't have to enter my creds every time I run it?  Is there a way I can test if I'm connected/authenticated?

2. How can I export this into a .csv rather that dumping comma-separated strings into a txt file?  This current method works well enough, but I'd like to extend/expand the script and want to eliminate the "import into Excel from text file" step (I had trouble trying to make an array of comma-separated strings).

thx in advance!

if(-not (Get-Module -name 'MSOnline')) {
    Import-Module MSOnline
}
$mscred = get-credential
connect-msolservice -credential $mscred

$domain = 'mydomain.com'
$licfile = 'c:\o365\Licenses.txt'

foreach($msusr in (Get-MSOLUser -All | Where-Object { (($_.isLicensed -eq 'True') -and
    ($_.UserPrincipalName -match $domain)) })) {
    foreach ($license in $msusr.Licenses)
    {
        $licinfo = ($($msusr.DisplayName) + ',' + $($msusr.UserPrincipalName) + ',' +
             ($($license.AccountSKUid).Split(':')[1]))
        Add-Content $licfile $licinfo
    }
}

Ping multiple servers from a list of IP addresses using Powershell and find out the least response time

$
0
0

Hi,

I have a CSV file wherein i have a list of IP addresses. I would like to use Test-Connection to ping 3 domain controllers one from each of my sites from each IP address in the list to verify which gives me the least response time. So the Test connection needs to be between each IP address in the CSV and three domain controllers. A script to compare the response time between the three with each IP and return the domain controller with the least for that IP address.

I used Test-connection like 

Test-Connection -Source Server02 -ComputerName Server01

where Server02 is the IP address in the CSV and Server01 is the domain controller. However i get the error : The RPC Server is unavailable.

Please help!!

Unable to change keyboard layout for all users on Windows Server 2012 R2

$
0
0

Hi,

I have a requirement where I need to support national keyboard layout for Danish for all users on that machine. When I ran the powershell with script Set-WinUserLanguageList -LanguageList da-DK it only sets the Danish keyboard layout to the specific logged in user.However the for other users its same English(US) keyboard which is not expected.

Please help me how to set the Danish keyboard for all users on the machine. Its Urgent!Thanks

Get-SmigServer Feature trouble shooting Windows Server 2003

$
0
0

I installed the Windows Server 2012 R2 Migration Tool (destination new server)  on a  Windows Server 2003 server, I then Created th SMT_ws03_x86 package since I need to migrate a DHCP Server from Windows Server 2003 to Windows Server 2012 R2. When I ran the Get-SmigServerFeatures

Here is the message I got.

PS C:\SMT_ws03_x86> Get-SmigServerFeature
Get-SmigServerFeature : Initialization of the migration failed.
The migration operation encountered an unknown exception.
At line:1 char:21

Get-SmigServerFeature Windows Server 2003 Migration

$
0
0

I installed the Windows Server 2012 R2 Migration Tool (destination new server)  on a  Windows Server 2003 server, I then Created th SMT_ws03_x86 package since I need to migrate a DHCP Server from Windows Server 2003 to Windows Server 2012 R2. When I ran the Get-SmigServerFeatures

Here is the message I got.

PS C:\SMT_ws03_x86> Get-SmigServerFeature
Get-SmigServerFeature : Initialization of the migration failed.
The migration operation encountered an unknown exception.
At line:1 char:21


It seems like updates described in the KB3057134 make PowerShell to start slow

$
0
0

Starting this morning it takes 3-4 seconds to start even very simple PowerShell script on my machine. This command shows 3.2-3.4 seconds on my machine and only 0.4 second on co-worker's machine.

powershell ( Measure-Command { powershell "Write-Host 1" } ).TotalSeconds

I know there are thousands of possible reasons (including viruses!)... But I don't see any suspicious activity on my machine, and I've installed a bunch of Windows updates this morning, and it was the only significant change in my environment.

I'm wondering if anybody has the same problem.

UPDATE

It seems like updates described in the KB3057134 make PowerShell to start slow.

After I installed these updates the following command took 3.4 seconds, Normally it takes no more than 0.4 seconds:

powershell -NoProfile ( Measure-Command { powershell -NoProfile "Write-Host 1" } ).TotalSeconds

After I removed these updates the problem disappeared, and this command show 0.3-0.4 seconds as expected.

The problem exists both Win7 and Win8.1 and affects both PowerShell 3.0 and PowerShell 4.0.

P.S. https://connect.microsoft.com/PowerShell/feedbackdetail/view/1332211/

How to export all Groups and their "msExchGroupExternalMemberCount" Attributes to csv file

$
0
0

Would really appriciate help pulling the Exchange Attribute "msExchGroupExternalMemberCount" for all groups to a csv file.  I have not been able to figure out a powershell script which would pull this data.  The -Properties switch only pulls general properties.

We have been having an issue with our mailtips for external receipients falsely flagging groups as having external members when they do not and are looking to pull a list of all groups and their "msExchGroupExternalMemberCount" attribute.

Thank you!

Collection of non standard PowerShell objects - how ?

$
0
0

Hi!

I write PowerShell advanced function to to query Active Directory using Exchange 2010 management shell (PowerShell 2.0).

In my function I query recipients and next for any recipient I take email addresses (proxy addresses). As a results  as a result I would like create custom objects collection.

For create any item for collection I use construction like this

$Result = New-Object PSObject

$Result | Add-Member -Type 'NoteProperty' -Name RecipientIdentifier -Value $CurrentRecipientIdentifier

$Result | Add-Member -type 'NoteProperty' -name RecipientAlias -value $CurrentRecipient.Alias

next I enumerate addresses by prefixes (using loops) and create next properties for $Result variable e.g.

[String]$CurrentPrefixAddressCountColumnName = "{0}{1}{2}" -f "AddressesForPrefix_", $CurrentPrefix, "_Count"

$Result | Add-Member -Type 'NoteProperty' -Name $CurrentPrefixAddressCountColumnName -Value $EmailsWithPrefixCount

at the end I add my $Result to $Results variable (which is intialized as $Results = @() ) using $Results += Result .

And the issue is that $Results has only properties which were added by the first $Result subobject

The full function is published at  GitHub .

Thank you in advance for any help.

      


Wojciech Sciesinski

Not enough quota is available to process this command.

$
0
0


Hi, I'm trying to run a script in a remote Powershell session and I get a 'Not enough quota is available to process this command.' error. The symptoms are identical with the one reported in this bug:

https://connect.microsoft.com/PowerShell/feedback/details/775399/quotas-ignored-after-wmf-3-0-update

but I'm using Powershell 4.0 and the hot fix is not being installing against my Powershell:

http://support.microsoft.com/hotfix/KBHotfix.aspx?kbnum=2842230&kbln=en-us

This is how I'm calling the remote script:

$cred = Get-Credential
Enter-PSSession remote1 -Authentication CredSSP -cred $cred
cd d:\dev
.\Build.ps1


Instead of calling the .\Build.ps1 the error can be simple reproduced with this line:

cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd

cmd : Not enough quota is available to process this command.
    + CategoryInfo          : NotSpecified: (Not enough quot...s this command.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

Deleting a few cmds from the above line will make the rest of them to run.

I tried changing the MaxMemoryPerShellMB and MaxProcessesPerShell limits but nothing works:

winrm set winrm/config/winrs '@{MaxProcessesPerShell="10000"}'
winrm set winrm/config/winrs '@{MaxMemoryPerShellMB="2048"}'


Remotely executing a Backup-CARoleService returns a Access Denied after what appears to be successful execution.

$
0
0

I am trying to understand what is going on with my current script which is a simple one liner. My setup is relatively simple. An AD joined server that is going to be used as a certificate root in an internal PKI (The root server should be a workgroup only system, but let us move on.) running Windows 2012 R2, and a Windows 8.1 workstation that I am using as a RSAT/CnC system. I am able to launch a powershell as the administrator on the local system as well as remote into the server and launch powershell as the administrator.

If I run an invoke-command -Computer RemoteServer -ScriptBlock {Get-Culture} I get back the expected 4 columns of information. If I Enter-PSSession -Computer Remote Server and then issue Get-Culture, I get back the expected 3 columns of information (no remote system name).

The Problem is if do an invoke-command -Computer RemoteServer -ScriptBlock {Backup-CARoleService c:\testdir -Password (ConvertTo-SecureString "SuperSecret" -AsPlainText -Force)} or I run the script block from a Enter-PSSession prompt, it appears to execute properly (I get all of the proper files), but I get :

Backup-CARoleService : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
At line:1 char:1
+ Backup-CARoleService c:\testdir -Password (ConvertTo-SecureString "SuperSecret ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Backup-CARoleService], UnauthorizedAccessException
    + FullyQualifiedErrorId : BackupDatabase,Microsoft.CertificateServices.Administration.Commands.CA.BackupCACommand

at the end of execution.

If I remote terminal into RemoteServer and execute the Backup-CARoleService command from a powershell, everything succeeds without error.

What is going on with the Access Denied message ?

Thank you for your help.

Edit2 : I am the same domain user on both the local workstation and the remote server.

Edit3 : On a lark I also tried using :

$s=New-PSSession -Computer RemoteServer -Credentials Domain\Admin 

Invoke-Command -Session $s -ScriptBlock...

Same error message with these command.

Sean



Powershell command not recognized

$
0
0

Hello!

I'm trying to run a simple PowerShell script in order to add mailboxes to users who do not yet have them. I followed a tutorial I found, and tried to run the following command:

<tt>Get-User -RecipientTypeDetails User -OrganziationalUnit antti.local/UserCreator | Enable-Mailbox</tt>

However, when I run it, I get a following error:

"The term 'Get-user" is not recognized as a name of cmdlet..."

I looked into it, and found out that my Powershell does not support said command. However, I could find somewhat familiar command, Get-ADUser. However, after I change the command to begin with Get-ADUser, I get the following error:

"A parameter cannot be found that matches parameter name -RecipientTypeDetails"

After further inspection, I came to a conclusion that the command doesn't work since it was written for Windows Server 2008 R2. I'm using Windows Server 2012 R2 and Exchange Server 2013 myself. Has the PowerShell syntax changed between those versions of Windows or am I just doing it wrong somehow?

What kind of command should I use in order to get it work?

Thank you in advance!

Printing list of the certain pdf files from two folders

$
0
0

Hi folks,

I have a working script:

$ex = New-Object -ComObject Excel.Application
$ex.Visible = 1
$wb = $ex.Workbooks.Open("C:\Users\meli\Desktop\Eli-column.xlsx")
$ws = $wb.Worksheets.Item(1)

$result = @()

[int]$rmax = $ws.Range("G65536").End(-4162).Row
$ws.Range("G1:G$rmax") | Where {$_.Value2} | Foreach {
	$col = $_.Column+1
	$row = $_.Row
	$val = $ws.Cells.Item($row,$col)

	$result += [pscustomobject]@{
		Invoices = $_.Value2
		Values = $val.Value2
	}
}

$result | Where {!$_.Values} | Foreach {Start-Process -FilePath "s:\Invoices-SD-from-documentum\0070\$($_.Invoices).pdf" –Verb Print}
$ex.Quit()

that selects certain numbers of invoices,   and prints appropriated PDF files  from the 1 folder. How to change the script so that he was looking for invoices numbers ( pdf  files) in two folders and print them


nesher13


Need help with a script that Uninstalls SCCM CLient

$
0
0

Hello,

I pieced together a script that uninstalls the SCCM client on remote machines listed in a text file. WHen I run the script the CCM client uninstalls fine. At the end of the uninstall the c:\windows\ccm and c:\windows\ccmsetup folders are still there and need to be deleted manually. I added in a few lines to the script to delete those folders but I keep getting a "The system cannot find the file specified." error for both RD commands. ANy suggestions? Is there a better way to write the script? TIA

$Computers = Get-Content C:\CMClientProject\Computers.txt
$PsExecPath = "C:\CMClientProject\PsExec.exe"
ForEach($computer in $computers){
    $mystring=@"
    $($PsExecPath) \\$($computer) -u domain\user -p password "C:\Windows\ccmsetup\ccmsetup.exe" /uninstall
"@
   $removeCCMSETUPFolder=@"
    $($PsExecPath) \\$($computer) -u domain\user -p password RD c:\Windows\ccmsetup /s /q
"@
   $removeCCMfolder=@"
    $($PsExecPath) \\$($computer) -u domain\user -p password RD C:\Windows\CCM /s /q 
"@

    invoke-expression $mystring
    invoke-expression $removeCCMSETUPFolder
    invoke-expression $removeCCMfolder
    
    
    
    
}

MySQL query - data retrieved is sometimes empty (that's ok) but is not null and has length of 1, can't compare to data

$
0
0

I know the title is awful and I apologize.

Using the MySQL.NET connector to query a DB.  Here is the query (Query is my function that makes the actual query)

$checkDB = Query -Query "select status,started,error,clone_time,vm_uuid,built from BUILDS where id= '$ID'"

After creating a test record and querying the DB, if I output $checkDB I get the following:

status     : requested
started    :
error      :
clone_time : 0
vm_uuid    :
built      :

However, if I try to compare started, error, vm_uuid, or built to other variables, I am unable to.  Those values aren't $null, they have a length of 1.  Also, when they are populated with data and I query again, they still have a length of 1.  I'm running software test to verify the DB has some information (I won't know what is supposed to be there, I just want to verify something is there), but I can't figure out how to check and make sure for example that 'started' has a time stamp, and that 'vm_uuid' is populated, and that 'built' has a time stamp.  

I am not sure why the data looks that way or what I can do about it to compare to other data later on and run my tests.



help creating a power shell script to search for specific application on servers in a domain

$
0
0

Hi,

I was looking to create a power shell script to search servers on our domain in a certain IP address range(or OU if IP range would be to complex) for a certain application "CTERA" which we want to find out where this application is so we can uninstall it as we are not using it for a backup solution anymore.

I came across an article in my searches:  

http://blogs.technet.com/b/heyscriptingguy/archive/2013/11/15/use-powershell-to-find-installed-software.aspx

that talks about using the following format to find apps by checking the registry.

I created a script that would run on a server and find it for one computer using name.  Now the problem with this is I had to go the test server in question and use the enable-psremoting.  which in our case this would not be practical so I am not sure the invoke command would be a good way to do this, unless I can figure out a way to make the servers in this sub net or OU allow for the invoke command.

Basically looking for script that will allow me to search servers in our domain to see if an application is installed so I can then manually go to the servers and uninstall it.

Any ideas on best way to approach this via powershell?

=================

PS C:\Windows\system32> Invoke-Command -cn Server12-Server -ScriptBlock {Get-ItemProperty HKLM:\Software\wow6432Node\CTERA\*
 |Select DisplayName, Publisher, InstallDate}


DisplayName        :
Publisher          :
InstallDate        :
PSComputerName     : Server12-server
RunspaceId         : xxxxxxxxxxxxxxx-xxxxxxxxxxx
PSShowComputerName : True



PS C:\Windows\system32>

======================================

need help, script t0 pull the details of Terminal server license server configured on list of terminal severs.

$
0
0

Sccripting gurus..

I need help with a script that can pull the details of Terminal server license server configured on list of terminal severs. 

Terminal Servers are all windows server 2003 x63

Getting registry values to html

$
0
0

I'm trying to query the registry and converting to HTML.  If I don't convert to html, I get my result, but if I convert to html I just get an "*".  Can someone help me out.

$RegKey = "HKLM:\SYSTEM\CurrentControlSet\services\SNMP\Parameters"
$vc = get-itemproperty "$regkey\validcommunities" | Select * -Exclude PS*
$vc | ConvertTo-Html | out-file $home\desktop\test.html

Viewing all 21975 articles
Browse latest View live


Latest Images

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