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

PowerShell Remoting [CredSSP]: HTTP 500 from WinRM Service

$
0
0

I started getting HTTP 500 messages from the Windows Remote Management (WinRM) service on all of my test Windows Server 2012 systems, butonly when trying to use CredSSP (Credential Security Support Provider) to authenticate to the remote system. I can successfully establish a standard, Kerberos remote session, and I can also successfully establish SSL connections to them, using the -UseSSL switch parameter on the Enter-PSSession cmdlet.

The error message I'm getting, when I try to run:

$Cred = Get-Credential;
Enter-PSSession -ComputerName server01.contoso.com -Authentication CredSSP -Credential $Cred;

Is this:

Enter-PSSession : Connecting to remote server server01.contoso.com failed with the following error message : The WinRM
client received an HTTP server error status (500), but the remote service did not include any other information about
the cause of the failure. For more information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1+ Enter-PSSession -ComputerName server01.contoso.com -Authentication Credssp -Creden ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : InvalidArgument: (server01.contoso.com:String) [Enter-PSSession], PSRemotingTransportExcep
   tion+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed

So far, I have tried:

1. Disabling all GPOs related to credential delegation, WinRM configuration, and PowerShell
2. Disable-PSRemoting -Force;
3. Disable-WSManCredSSP -Role Client;
4. Disable-WSManCredSSP -Role Server;
5. Enable-PSRemoting -Force;
6. Set-WsmanQuickConfig -UseSSL;
7. On client: Enable-WsmanCredSSP -Role Client -DelegateComputer *.contoso.com;
8. On remote system: Enable-WsmanCredSSP -Role Server;

On the client system, in the Windows Remote Management event log, I'm seeing this message: WSMan operation CreateShell failed, error code 2150859120

In this scenario, both the client and server are running Windows Server 2012, withPowerShell v3.0.

Any thoughts on this error?


If this post was helpful, please click the little "Vote as Helpful" button :)

Trevor Sullivan
Trevor Sullivan's Tech Room
Twitter Profile




[15.00.670.4000] [PS] [C#] [Windows]: PowerShell Runspace to Exchange Online Budget Exceeded Error

$
0
0
I have an application that programmatically invokes PowerShell commands on Exchange Server. Connecting the app to Exchange online server outlook.office365.com is successful, and invoking individual commands works, but sending several commands in a sequence in a short period of time, server becomes clogged and replies with the message bellow. 


I tried with runspace.Close and runspace.Dispose, but it has no effect. 
From the message bellow, I see there is a maximum of 5 runspaces in 60 sec period, but with my code I am closing and disposing runspaces and that limit shouldn't be and issue. Of course, there is always a chance that I am doing something wrong.


message (some text is masked with dots):


   

  Connecting to remote server failed with the following error message : Fail to create runspace because you have exceeded your budget to create runspace. Please wait for 45 seconds.

Policy: CN=GlobalThrottlingPolicy_....,CN=Global Settings,CN=ExchangeLabs,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=namprd05,DC=prod,DC=outlook,DC=com; Snapshot: Owner: Sid~NAMPR05A001\.......~WSMan~false BudgetType: WSMan ActiveRunspaces: 0/3 Balance: 600000/1800000/-3000000 PowerShellCmdlets199/200 ExchangeCmdlets9223372036854775807/Unlimited CmdletTimePeriod: 5 DestructiveCmdlets60/Unlimited DestructiveCmdletTimePeriod: Unlimited QueueDepth: Unlimited MaxRunspaces: 5 MaxRunspacesTimePeriod: 60 LastTimeFrameUpdate: 4/23/2013 8:48:20 PM LastTimeFrameUpdateDestructiveCmdlets: 4/23/2013 8:40:36 PM LastTimeFrameUpdateMaxRunspaces: 4/23/2013 8:48:08 PM Locked: False LockRemaining: 00:00:00 For more information, see the about_Remote_Troubleshooting Help topic





Here is the simplified code (actual is more complex, but basically this is it):


    private Collection<PSObject> GetUser(string userName, string password)
    {
        try
        {
            serverName = "https://outlook.office365.com/powershell-LiveID?PSVersion=2.0"
            SecureString pass = new SecureString();
            foreach (char x in password.ToCharArray())
            {
                pass.AppendChar(x);
            }
            WSManConnectionInfo connectionInfo = new WSManConnectionInfo(
                new Uri(serverName), PSNamespace, new PSCredential(userName, pass));
            connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
            connectionInfo.SkipCNCheck = true;
            connectionInfo.SkipCACheck = true;
            CallContext.SetData("WSManConnectionInfo", connectionInfo);
            using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
            {
                using (PowerShell powershell = PowerShell.Create())
                {
                    try
                    {
                        powershell.AddCommand("Get-User");
                        powershell.AddArgument(userName);
                        runspace.Open();
                        powershell.Runspace = runspace;
                        return powershell.Invoke();
                    }
                    catch (Exception e)
                    {
                        return null;
                    }
                    finally
                    {
                        runspace.Close();
                        runspace.Dispose();
                    }
                }
            }
        }
        catch (Exception e)
        {


            return null;
        }
    }


Thanks,

Boris


Script running differently in PowerShell ISE vs. PowerShell command line. IF commands are being skipped in command line.

$
0
0

Hello.  I've been trying to figure this one out.  I wrote the script in ISE then scheduled it to run but it did not run as expected.  When i test run it in ISE it runs fine because the IF commands run no problem.  At the command shell the IF is skipped.   I may be missing something simple here. I appreciate any assistance. 

Script: (The two Outputs are below)  Note that Step 4 is inside the IF statement.

This script checks to see if exchange database replication has any issues on any of the databases.  If there is an issue, the IncomingLogCopyingNetwork field is very long.  If no issue, it is under 15 characters.

write-output "Step1, Populate databaselist"
    $databaseList = Get-MailboxDatabaseCopyStatus -server caprgmkmwembx1 -connectionstatus | select-object databasename,name, IncomingLogCopyingNetwork
write-output "Step2, Set DBProblemCount to 0"
$DBProblemCount = 0

        foreach($databasename in $databaseList)
            {
            
            write-output "Step3, Inside ForEach"
            if ($databasename.IncomingLogCopyingNetwork.length -gt 25)
                {
                write-output "Step4, Inside IF"
                $DBProblemCount++
                write-output $DBProblemCount    
                }
            }    


    if ($DBProblemCount -gt 1)
    {
    write-output "Step5, Send Email Message."
    #Send-MailMessage <Truncated for posting>
    #write-output $DBISSUELIST
    Send-MailMessage <Truncated for posting>
    }
write-output "Step6, Send Email Message to State Script has run."
Send-MailMessage <Truncated for posting>

PowerShell ISE Output:

Step1, Populate databaselist
Step2, Set DBProblemCount to 0
Step3, Inside ForEach
Step4, Inside IF
1
Step3, Inside ForEach
Step4, Inside IF
2
Step3, Inside ForEach
Step4, Inside IF
3
...Truncated the incremental numbers.
46
Step3, Inside ForEach
Step4, Inside IF
47
Step3, Inside ForEach
Step4, Inside IF
48
Step3, Inside ForEach
Step4, Inside IF
49
Step5, Send Email Message.
Step6, Send Email Message to State Script has run.

PowerShell Shell Output:

Step1, Populate databaselist Step2, Set DBProblemCount to 0 Step3, Inside ForEach Step3, Inside ForEach Step3, Inside ForEach

...Truncated the incremental.

Step3, Inside ForEach Step3, Inside ForEach Step3, Inside ForEach Step3, Inside ForEach Step3, Inside ForEach Step6, Send Email Message to State Script has run.



~~~ Mark Orser Pernod Ricard Americas

Sensational! Discovering Useful Console Commands.

Sensational! Listing Windows Updates with PowerShell.

Using Powershell to run ExBPACmd

$
0
0

i am trying to set up a powershell script to run ExBPACmd and output to a file and on top of that it would be great if i could get it to email me when done.

Has anyone tried this or have ideas on how? i am new to powershell and still learning.

Problems with variables

$
0
0

Hello.

So, I've been working with Powershell for about a week.  Finally decided to dive in, and I'm stuck

What I'm trying to do is grab all the services running as a domain account and run that through Get-ADUser to grab some of the properties for that account.  Problem #1 is the script below comes back with the domain appended to the front:  AB\ServiceAccountName

Get-WmiObject -ComputerName $StrComputer Win32_Service | select-object startname | Where-Object {$_.startname -like "AB\*"}

$ServiceAccount=$_.startname

Get-ADUser doesn't like the AB\ in front of the name (or if it does, I'd love to know how).  So, I've looked at stripping off the first three characters, AB\, and passing that to Get-ADUser via this:

$ServiceAccount=$ServiceAccount.Substring(3)

This gives the error:

Method invocation failed because [Microsoft.ActiveDirectory.Management.ADPropertyValueCollection] doesn't contain a method named 'substring'.
At line:6 char:42
+ $serviceaccount=$serviceaccount.substring <<<< (3)
    + CategoryInfo          : InvalidOperation: (substring:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

I'm at a loss.  Any help or pointing in the right direction would be greatly appreciated.

Using a variable for $db.SetOwner

$
0
0

Does anyone know how I can use a variable for this?

$owner = "someowner"
$srv = new-Object Microsoft.SqlServer.Management.Smo.Server($destinationInstance)
$db = New-Object Microsoft.SqlServer.Management.Smo.Database
$db = $srv.Databases.Item($sourceDbName)
$db.SetOwner($owner, $TRUE)

Gives me errors when I try the above.

If I use $db.SetOwner('sa', $true) is works but I need to hold a variable.




Enter-PSSession UriFormatException

$
0
0
I am attempting to install Remote Desktop Services in Windows Server 2012 and am getting a fail on "Specify RD Connection Broker Server". The compatibility check failed with "Unable to connect to the server by using Windows PowerShell remoting. (I don't normally use power shell.)

The Server name is "Test.<domainname>._internal".

When I try to connect with power shell and a manual PSRemoting command, using "Test", it connects. When I try the full name, it fails with:

enter-pssession : Invalid URI: The hostname could not be parsed.
At line:1 char:1
+ enter-pssession test.<domainname>._internal
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Enter-PSSession], UriFormatException
    + FullyQualifiedErrorId : System.UriFormatException,Microsoft.PowerShell.Commands.EnterPSSessionCommand
I get the same results from both the server itself and from the domain controller to the test machine.

Can't PowerShell use standard DNS resolution and handle FQDN's? Or can't it handle the underscore ("_").

Any ideas?

Thanks,
Bob.

PS: <domainname> is the place holder for the actual domain name.

Help with putting together a list of AD computers

$
0
0

I am trying to put together a list of servers on our domain that will list the server name,  description, and the OS version.  I am having trouble adding multiple filters in.  So far i have a list of all my 2008 servers.  Any help is appreciated.

Get-ADComputer -filter {OperatingSystem -like "*2008*} | Select-Object name | export-csv list.csv

AD users that have never logged on showing their passwords are pre-expired

$
0
0

Hi, I trying to get information about never logged users in AD on showing their passwords are pre-expired, could someone verify script below, is it fine or I should add anything else?

get-aduser  -properties * -f {-not (lastlogontimestamp -like "*") -and (enabled -eq $true) -and (PasswordNeverExpires -eq $false)} | select-object name, passwordExpired, PasswordNeverExpires,SAMaccountname, lastlogondate, lastlogontimestamp, logoncount, whenCreated, PasswordLastSet 


AG

Get folders size on multiple users

$
0
0

Hi i got a script to find the folder size of multiple users and create a new object with desired properties.

$users = Get-ChildItem \\myserver\homefolders | select name

$outfile = @()

foreach ($user in $users) {

$colItems =  (Get-ChildItem '\\myserver\homefolders\$user\documents\My Music\$RECYCLE.BIN' -force -recurse |  Measure-Object -property length -sum)
$docsize = "{0:N2}" -f ($colItems.sum / 1MB) + " MB"




$o = new-object PSObject

     $o | add-member NoteProperty 'name' $user
     $o | add-member NoteProperty 'docsize' $docsize 

     $outfile += $o

}


When i run it i get an error :

Get-ChildItem : Cannot find path '\\Myserver\homefolders\@{Name=user1}\documents\RECYCLE.BIN' because it does not exist.

I know the folder exists, so why is it failing?

Thanks

change DNS script, can't make it update description variables

$
0
0

My environment is a static IP one and I must change the DNS settings on all the WinXP and Win7 clients. I pretty much have the gist of the script down except maybe part of the loops.  The first loop just checks to see if the PC is accessible, then runs thru a text file with all the hosts and should output the hostname and the NIC description for each. The problem is that the $nic.description is always the same for each machine even though there are several different NICs in use here. Most of them are Intel(R) 82579LM but I know that most of the laptops should come back saying Inter(R) Centrino(R) - but EVERYTHING is saying 82579 so i'm not convinced this is working right. My text file only has 3 PCs and 1 laptop in it while I test this, before I commit the command to all 2000 machines get false positives.

$servers = get-content c:\pc.txt
$nics = get-wmiobject win32_networkadapterconfiguration | where-object {$_.DHCPEnabled -eq $False -and $_.IPAddress -gt 1}
$newDNS = "10.100.67.137","10.100.67.224"
foreach($server in $servers)
{
if (Test-Connection -ComputerName $server -Count 1 -quiet)
 {
   Write-Host ""
   Write-Host "Connecting to $server..."
   foreach($nic in $nics)
   {
      Write-Host "`tExisting DNS Servers on" $server $nic.description "was" $nic.DNSServerSearchOrder
      $x = $nic.SetDNSServerSearchOrder($newDNS)
      if($x.ReturnValue -eq 0)
      {
         Write-Host "`tSuccess! Changed DNS on" $server $nic.description "now" $newDNS
      }
      else
      {
         Write-Host "`tFailed to change DNS on" $server
      }
   }
 }
 else
 {
    write-host ""
    write-host "Failed to connect to " $server
 }
}

Search for string in Array

$
0
0

Hi,

I've made a start, I want to search for a process name running on many servers, here is what I have

# exe's to check
$1 = "jews_did_wtc.exe", "KMS.exe","fud.exe", windongs.exe","dragondildo.exe","wc.exe","windos.exe","butt.exe",wincap.exe","911.exe","zzz.exe"


$serverlist = get-content dns_-wf.txt
foreach ($server in $serverlist) {
$services = get-service * -computername $server

foreach ($exe in $1) { search through $services !?!?!?!?

}

I have my arrays just need a syntax for searching them for the contents of $1

Thanks


Alter De Ruine

How to run a power shell scipt in a remote pc

$
0
0

Hi All,

Below is my code to execute powershell scripts wih aguments using C#.
Now i want to run scripts in a remote pc. In the method i will be passing remoteserver and credentials
public static IList<string> ExecutePowerShellScript(string scriptname, string args,string remote server,string username,string password

Can any one tell me how to execute script in a server which i passing using the credentials that im passing in the method
Can write the code any send me.plzzz

Thanks in advance

public static IList<string> ExecutePowerShellScript(string scriptname, string args)
        {
            List<string> list = new List<string>();

            Runspace runspace = RunspaceFactory.CreateRunspace();
            runspace.Open();
            Pipeline pipeline = runspace.CreatePipeline();
            Command cmd = new Command(scriptname + " " + args, true);
            //Command cmd = new Command(scriptname);
            //cmd.Parameters.Add(args);

            pipeline.Commands.Add(cmd);

            Collection<PSObject> results;
            results = pipeline.Invoke();

            foreach (PSObject obj in results)
            {
                list.Add(obj.ToString());
            }

            return list.ToArray();
        }


adityadugyala


Trigger a Script on On Saturdays

$
0
0

I'm looking at writing a script that only fires off an email when it's either the first or second Saturday of the month..

All other Saturdays of the month can be ignored. The issue I'm having is that each Saturday has a value of 6 when using Get-Date.. So I need some way of ignoring the 3rd & 4th Saturdays of the month.....

So far I using a If statement and a count variable.. but the script still runs when the third Saturday is triggered... As i've reset the counter.... I'm trying to find the best logic to use for this case..

$StartOfMonth = Get-Date -Year $Year -Month $Month -Day $Day
$CurrentWeek = Get-Date -UFormat %V -Year $Year -Month $Month -Day $Day
[int]$DayInWeek = $StartOfMonth.DayOfWeek
Write-Host 'Day Of Week = ' $DayInWeek
Write-Host 'Starting Day Of Month = ' $StartOfMonth.Day
Write-Host 'Day of Week = ' $StartOfMonth.DayOfWeek
Write-Host 'Week = ' $CurrentWeek
$Saturday = $DayInWeek
	If($Saturday -eq 6 -and $Counter -eq 0) {
		Write-Host 'Day Is First Saturday Of Month' 'Day = ' $FirstSaturday 
		$Counter++
		Write-Host $Counter
	}
	ElseIf($Saturday -eq 6 -and $Counter -eq 1){
		Write-Host 'Second Saturday of the Month' 'Day =' $StartOfMonth.DayOfWeek
		$Counter ++		
	}

Any ideas...

Thanks,

Shaun.

Switching between DHCP & Static IP in Powershell

$
0
0

I am looking to run a Power Shell script that does the following:

1. Determine the active NIC and import it. Currently I am able to find the active NICs with this command -

Get-WmiObject -Class win32_NetworkAdapter -ComputerName LocalHost -Filter "NetworkConnectionStatus = 2" | Format-Table Name, NetEnabled, NetConnectionStatus, DeviceID -AutoSize

2. Ask the user which interface to use - if more than one active interface

3. Ask the user if they want a Static (If Static, have the option to enter the IP, Subnet Mask, & Default Gateway or use presets) or Dynamic IP then run one of the following commands

$NIC.EnableDHCP()

or

$NIC.EnableStatic("192.168.1.2","255.255.255.0")

If switching from DHCP to Static, it should first release the IP.

Thanks in advance,

Pat

Remote PowerShell Execution

$
0
0

We have an ADFS environment which our AD has a one-way sync with O365. Any changes we have to make, we have to do in AD. One of our consultants supplied us with two commands that allow us to force a sync between our AD up to O365.

 

Once I finish making changes in our AD:

    • On our server with AD, I go to Start --> Run --> repadmin /syncall /e:
    • Log off once the command window finishes running
    • Log into our ADFS server
        
  • Run a file called DirSyncConfigShell.psc1
    • This file contains the following code:
<?xml version="1.0" encoding="utf-8"?><PSConsoleFile ConsoleSchemaVersion="1.0"><PSVersion>1.0</PSVersion><PSSnapIns><PSSnapIn Name="Coexistence-Configuration" /></PSSnapIns></PSConsoleFile>
  • When you run that file, a black PowerShell command window opens
  • Type Start-OnlineCoexistenceSync and press enter.
  • Log off and the AD to O365 sync is completed

What I would like to know is if there is a way that I can do this from a single batch command, PowerShell or something. We do this frequently enough that it would be great to be able to run steps 4-6 right from our AD server. I know there is a tool call PSEXEC that supposed to let you remotely run commands but not sure how this would work. Both our AD server and ADFS server are on the same domain.

Anyone have any advice?

How to move huge amount of folders to limited number of folders

$
0
0

Dear PS gurus,

I tried to searched my question online but didn't get what I need.Thanks very much:

Suppose there are lots of folders insides a root folder(namely, D:\) with different sizes (but all less than 4GB). I need to move them to limited number of folders(still in D:\, with name like group1, group2,...) but each folder must be less than 4GB. I use PS version 3 in Windows 7. Thx.



What effect does -force have on Format-List?

$
0
0

What effect does -force (in general) have on Format-List?

For example, see the difference in these two commands

fl -inputobject $profile -force
fl -inputobject $profile



Viewing all 21975 articles
Browse latest View live


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