The following code works on our internal exchange server minus the connection bits as thats not needed on-prem. I have added connection code to 365, which works fine. When I run this, I get the following error and it forces me to login a second time and exports only a fraction of the results:
Starting a command on the remote server failed with the following error message : The I/O operation has been aborted
because of either a thread exit or an application request. For more information, see the about_Remote_Troubleshooting
Help topic.
+ CategoryInfo : OperationStopped: (ps.outlook.com:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : JobFailure
+ PSComputerName : ps.outlook.com
Processing data from remote server ps.outlook.com failed with the following error message: WS-Management cannot
process the request. The operation failed because of an HTTP error. The HTTP error (12152) is: The server returned an
invalid or unrecognized response . For more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OperationStopped: (ps.outlook.com:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : JobFailure
+ PSComputerName : ps.outlook.com
Below is the code I am attempting to use. Do I have it formatted wrong?
#Script Created by Daniel Taylor 8/8/18
#Set Location for export:
$fLocation = "C:\temp\"
#Get username and password for 0365 connection
$cred = get-credential
#Import microsoft online
Import-module msonline
#Connect to MSonline
connect-msolservice -Credential $cred
#Connect to exchange online
$EolSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri “https://ps.outlook.com/powershell/” -Credential $cred -Authentication Basic -AllowRedirection
Import-PSSession $EolSession -DisableNameChecking
Write-host "You are now connected to Exchange. Begning ActiveSync Export:" -ForegroundColor DarkGreen
#create File to write report to:
$fName = $fLocation+"ActiveSyncDevices.txt"
$test = test-path $fName
if ($test -eq $True)
{
write-host "Removing Old File..." -ForeGroundColor Red
Remove-Item $fName
}
#Else
#{
#New-Item $fName -type file
#}
Write-host "Creating New File..." -ForeGroundColor Green
New-Item $fName -type file
#Get ActiveSync and Mailbox data
$EASDevices = ""
$AllEASDevices = #()
$EASDevices = ""| select 'User','PrimarySMTPAddress','DeviceType','DeviceModel','DeviceOS', 'LastSyncAttemptTime','LastSuccessSync'
$EasMailboxes = Get-Mailbox -ResultSize unlimited
foreach ($EASUser in $EasMailboxes) {
$EASDevices.user = $EASUser.displayname
$EASDevices.PrimarySMTPAddress = $EASUser.PrimarySMTPAddress.tostring()
foreach ($EASUserDevices in Get-MobileDevice -Mailbox $EasUser.alias) {
$EASDeviceStatistics = $EASUserDevices | Get-MobileDeviceStatistics
$EASDevices.devicetype = $EASUserDevices.devicetype
$EASDevices.devicemodel = $EASUserDevices.devicemodel
$EASDevices.deviceos = $EASUserDevices.deviceos
$EASDevices.lastsyncattempttime = $EASDeviceStatistics.lastsyncattempttime
$EASDevices.lastsuccesssync = $EASDeviceStatistics.lastsuccesssync
$AllEASDevices += $EASDevices | select user,primarysmtpaddress,devicetype,devicemodel,deviceos,lastsyncattempttime,lastsuccesssync
}
}
$AllEASDevices = $AllEASDevices | sort user
$AllEASDevices | Export-Csv $fname
write-host "The script completed successfully! The output file can be found at $fName" -ForeGroundColor Yellow
You cannot be logged in to Exchange on-prem and Exchange online at the same time. They use the same cmdlet and on-prem will take precedence.
If you are using PSRemoting, you must use two different sessions, and it's best to prefix those, so they are unique.
Or, be on the Exchange server directly and do your thing there, and open a new PSRemoting session to O365, prefixed so that the proxied commands have the prefix name.
Then make your O365 calls with the proxied cmdlets, not the on-prem ones.
Example Session setup:
# Exchange PowerShell Remote Management
#
$creds = Import-Clixml -Path $CredPath
$ExchangeSession = New-PSSession -ConfigurationName 'Microsoft.Exchange' `
-ConnectionUri ('http://' + $ExchangeServerFQDN + '/PowerShell') `
-Authentication Kerberos -Credential $Creds.ExpAdmin
Import-PSSession $ExchangeSession -Prefix 'EXP'
$creds = Import-Clixml -Path $CredPath
$ExchangeOnlineSession = New-PSSession -ConfigurationName 'Microsoft.Exchange' `
-ConnectionUri 'https://outlook.office365.com/PowerShell-liveid/' `
-Authentication Basic -Credential $Creds.ExoAdmin -AllowRedirection
Import-PSSession $ExchangeOnlineSession -Prefix 'EXO'
Get-PSSession
Each of the command will have EXP or EXO as part of the name of the proxied cmdlets.
Again, if you are doing this directly on Exchange, you only need the EXO session, and use the on-prem Exchange cmdlets normally.
Related
Trying to manage our Remote Desktop Services installation using PowerShell and we're running into an issue where the commands in the RemoteDeskop module and the RemoteDesktopServices module do not appear to work when being run via Invoke-Command. Basically it appears that these functions do not work when run in a remote session.
The script below gets the following error:
The RD Connection Broker server is not available. Verify that you can
connect to the RD Connection Broker server.
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-RDServer
+ PSComputerName : AWSELABSDevX13.LABSDEV.com
$server = "OUR_SERVER"
$connection_broker = "OUR_SERVER"
$collectionName ="COLLECTION"
$admin_user = "FULLY_QUALIFIED_DOMAIN_USER"
$password = "PASSWORD"
$password_sec = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ($admin_user, $password_sec)
$sb =
{
function Test-IsAdmin {
([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
}
if (Test-IsAdmin) {
""
"You are running with Administrator access."
""
} else {
""
"You do not have admin access."
""
}
whoami /priv
Import-Module RemoteDesktop
Import-Module RemoteDesktopServices
Get-RDServer
}
Invoke-Command -Credential $cred -ComputerName $connection_broker -ScriptBlock $sb
I have the following script which until now worked just fine.
# Mailbox Migration Script
$ErrorActionPreference = "stop"
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010;
#$UserCredential = Get-Credential -Message "`n Please supply your O365 credentials using (Example: user#corp.mycorp.com): `n "
#$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
#Import-PSSession $Session
#Choose, USERNAME related to mailbox:
Write-Host "`n ATTENTION : THIS SCRIPT WILL SHUT DOWN IF YOU ENTER WRONG MAILBOX INFO `n OR THE MAILBOX HAS ALREADY BEEN MIGRATED." -for Red;
$username = Read-Host -Prompt "`n Please provide AD-USERNAME to Migrate";
Write-Host "`n The chosen user is:";
Write-Host "`n " $username -for Yellow;
Write-Host "`n Press ENTER key to confirm and continue. `n Press CTRL+C to cancel";
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
Now after running this, i get an error which crashes the script.
Exception calling "ReadKey" with "1" argument(s): "The method or operation is not
implemented."
At C:\Users\username\Desktop\PowerShell\Migration-prompt.ps1:19 char:1
+ $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordExcepti
on
+ FullyQualifiedErrorId : NotImplementedException
I imagine the issue should be somewhere on this line:
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
Your help would be mostly appreciated on fixing this.
Thank you very much !
Replace the troubled line with this one.
$null = Read-Host
If you want to troubleshoot the issue instead, start with the error. The method is not implemented. The PowerShell host has changed in some fashion. What is the output for $host?
I have a VM running Windows Server 2012.And some intended services on it. I want to change a configuration file on this VM machine remotely from my desktop pc.
Currently I change this configuration file by mapping the C: drive of the remote server and then changing the file. Now this blocks me from changing multiple servers as I can't map multiple server c: simultaneously to same drive. Also, mapping hundreds of drives wouldn't be ideal.
The way I am changing the file by mapping drive is:
$password = <password text> | ConvertTo-SecureString -asPlainText -Force
$username = "admin"
$credential = New-Object System.Management.Automation.PSCredential($username,$password)
net use Z: \\$ipAddress\C$ <password> /user:admin type 'z:\Program Files\lalaland\Data\Settings.xml'
(Get-Content 'z:\Program Files\lalaland\Data\Settings.xml') | ForEach-Object { $_ -replace $oldString, $newString } | Set-Content 'z:\Program Files\lalaland\Data\Settings.xml'
type 'z:\Program Files\lalaland\Data\Settings.xml'
net use z: /delete
Therefore I searched for a better option and found this script at https://gallery.technet.microsoft.com/scriptcenter/PowerShell-Replace-String-58fbfa85 but it doesn't work for me.
I am using this script as :
.\Replace-StringInFile.ps1 -ComputerName <RemoteComputerHostName> -TargetPath 'C:\Program Files\lalaland\Data' -Fil
eName Settings.xml -Replace $oldString -ReplaceWith $newString -Credential (Get-Credential)
when I run the command credential window pops up asking for username and password. I enter the username and password that I used for mapping the drive, but it throws the following error:
New-PSSession : [<RemoteHostName>] Connecting to remote server <RemoteHostName> failed with the following error message : The user name or password is incorrect. For more information, see the
about_Remote_Troubleshooting Help topic.
At D:\workspace\Replace-StringInFile.ps1:84 char:14
+ ... $Session = New-PSSession -ComputerName $Computer -Credential $Creden ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : LogonFailure,PSSessionOpenFailed
what I don't understand is when I map the drive with the same credentials it works fine but using the other script, which internally uses New-PSSession doesn't work.
Any idea ?
I was able to do this using the following cmdlet:
function Edit-RemoteFileStringReplace
{
[cmdletbinding()]
param([Parameter(Mandatory=$true)][ValidateScript({$_ -match [IPAddress]$_ })][string]$Address,
[Parameter(Mandatory=$true)][string]$FilePath,
[Parameter(Mandatory=$true)][string]$Replace,
[Parameter(Mandatory=$true)][string]$ReplaceWith,
[Parameter(Mandatory=$true)][System.Management.Automation.PSCredential]$Credential
)
$DriveLetter=""
$FilePathWithoutDriveLetter=""
$DriveName = $Address.replace('.','x')
$DriveName = "PSDrive_$DriveName"
$DriveLetter = (Get-DriveLetterFromPath -Path $FilePath).Substring(0,1)
$FilePathWithoutDriveLetter = Remove-DriveLetterFromPath -Path $FilePath
$MappedFilePath="$DriveName" + ":$FilePathWithoutDriveLetter"
New-PSDrive -Name $DriveName -PSProvider FileSystem -Root \\$Address\$DriveLetter$ -Credential $Credential -ErrorAction Stop
(Get-Content $MappedFilePath) | ForEach-Object { $_ -replace $Replace, $ReplaceWith } | Set-Content $MappedFilePath
Remove-PSDrive -Name $DriveName
}
I have a Power Shell script that sits on a VM and creates a PSSession to a physical machine and runs a batch file. Running the batch file directly in the physical machine works as expected, however when I try running it remotely from the VM is it throwing up error.
Power Shell:
$Username = "Domain\User"
$Password = ConvertTo-SecureString "Password*" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ($Username, $password)
$session = New-PSSession -ComputerName "K2" -Credential $cred
Enter-PSSession -Session $session
Invoke-Command -ComputerName "K2" -ScriptBlock {
Set-Location 'C:\Program Files\SmartBear\ReadyAPI-2.4.0\Go4Schools Tests\Test Runner'
& '.\PSTR.bat'
}
Exit-PSSession
Get-PSSession | Remove-PSSession
Batch File:
"C:\Program Files\SmartBear\ReadyAPI-2.4.0\bin\testrunner.bat" -A -j "-fC:\Users\administrator.HYPERSPHERIC\Desktop\Go4Schools Tests\Test Results" "-RJUnit-Style HTML Report" -FXML -EDevTest "C:\Users\administrator.HYPERSPHERIC\Desktop\Go4Schools Tests\Project Saves\SoapUI_Mobile_API_Project.xml"
Error:
PS C:\> C:\Users\administrator.HYPERSPHERIC\Desktop\PS_TR.ps1
C:\Program Files\SmartBear\ReadyAPI-2.4.0\Go4Schools Tests\Test Runner>"C:\Program Files\SmartBear\ReadyAPI-2.4.0\bin\testrunner.bat" -A -j "-fC:\Program Files\SmartBear\ReadyAPI-2.4.0\Go4Sch
ools Tests\Test Results" "-RJUnit-Style HTML Report" -FXML -EDevTest "C:\Program Files\SmartBear\ReadyAPI-2.4.0\Go4Schools Tests\Project Saves\SoapUI_Mobile_API_Project.xml"
Error: Could not find or load main class com.smartbear.ready.cmd.runner.pro.SoapUIProTestCaseRunner
+ CategoryInfo : NotSpecified: (Error: Could no...oTestCaseRunner:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName : K2
Ready API and soapUI use some environment variables in testrunner.bat to set up dependencies and the like. So, whenever I've executed testrunner.bat with a script from outside of the application, I've always CD'ed to the bin directory first:
cd <Ready API installation directory>\bin
./testrunner.bat ...
I have a strange problem with one of my servers :
I am trying to open a PSsession with it.
If I copy my script directly in powershell everything works fine, but if i run it via a .ps1 file I get a access denied error.
The same sript works on multiple machines except this one.
Additonal information:
Executing Server : Server 2012
Target Server2003SP2
Another Server2003SP2 is working fine without a Problem
the Client Server was configured using :
Enable-PSRemoting -Force
Set-Item wsman:\localhost\client\trustedhosts MY2012Server -concatenate -force
Restart-Service WinRM
And the Error Message:
New-PSSession : [Server2003SP2] Connecting to remote server Server2003SP2 failed with the following error message : Access is denied. For more information,
Help topic.
At C:\Users\Administrator\Desktop\Script.ps1:23 char:13
+ $Session = New-PSSession -ComputerName $Servername -credential $Cred #-sessionO ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed
Edit : My full SCript as requested :
$Password = "Hereismypasswordwith#and€init"
$Username = "Servername\Administrator"
$Servername = "Servername"
$Language = {
$oscode = Get-WmiObject Win32_OperatingSystem -ErrorAction continue
$oscode = $oscode.oslanguage
$switch = switch ($oscode){
1031 {"Deutsch"};
1033 {"English"};
default {"English"};
}
write-host $switch
return $switch
}
$SecurePassWord = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $Username, $SecurePassWord
$pssessionoption = new-pssessionoption -operationtimeout 7200000 -IdleTimeout 7200000
$Session = New-PSSession -ComputerName $Servername -credential $Cred -sessionOption $pssessionoption
Invoke-Command -Session $Session -Scriptblock $Language
Remove-PSSession -Session $Session
UPDATE :
it seems to be something within the Char encoding.
the password in the ps1 file produces a difrent output for the € in it :
in the ps1. ¬
in the ps window : ?
if i pass the Password as a Paramter it also works.
$password.gethash() also prouces difrent outputs. codepage is the same though (chcp)
the script was created in notepad++
Changing / Converting to ansi from UTC without BOM fixed the issue.. jesus crist who thinks about stuff like that / why the hell was it set to this value..