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?
Related
I created a short PowerShell scrtipt in order to import a .reg file (an ODBC) to another server session.
I faced to this warning/issue.
The message is this (below):
The operation completed successfully.
+ CategoryInfo : NotSpecified: (The operation completed successfully.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName : MYSERVERNAME
NotSpecified: (:) [], RemoteException
The script, install without problem the .reg file, but constantly I get the message.
This is my code:
#PARAMETERS - Variables
$Serverlist = Get-Content C:\ServerList.txt
try
{
Foreach ($ServerName in $Serverlist)
{
$session = New-PSSession -ComputerName $servername
Write-Host -Foregroundcolor Green "Copying ODBC Driver for $servername"
$copy_cmd = "C:\MYFILE.reg"
Copy-Item $copy_cmd \\$servername\C$\ -recurse -force;
Write-Host -Foregroundcolor Green "ODBC Successfully copied on $servername"
#$session = New-PSSession -ComputerName $servername
Invoke-Command -Session $session -ScriptBlock {
#Start-Process
reg import C:\CopiedFile.reg #This line generate the message
Write-Host -Foregroundcolor Green "ODBC was installed
}
catch
{
Write-Host "ERROR" -Foregroundcolour Red
exit
}
I tried to incapsulate the Invoke-Command or reg import in to try - catch statement, but the message still appear. I used another command, instead reg import, but the nothing change.
I can use this command line, but I would like to catch the error.
Write-Host -Foregroundcolor Green "ODBC is installed " } ##-ErrorAction SilentlyContinue
There is any way to get the eventually error or handle the message.
Thanks in advance.
If the try block does not generate a terminating error, it will not move into the Catch block. This is controlled by -ErrorAction parameter. So you can set
Invoke-Command Session $session -ScriptBlock {} -ErrorAction Stop
This will cause the Invoke-Command Cmdlet to generate terminating errors(if any error occurs) allowing catch block to execute.
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.
I need to remotely run powershell commands on multiple windows servers using SysInternal tools but I tried a lot but it seems not to work . Any help is highly appreciated .
Servers.csv (file content)
10.10.10.100
10.0.0.111
Code :
$List = Import-CSV -Path "C:\Users\javed\Desktop\New\servers.csv"
foreach ($entry in $List) {
if (test-Connection -Cn $($entry.Name) -quiet) {
& C:\Users\javed\Downloads\PsTools\psexec.exe \\$($entry.Name) -u "$($entry.Name)\Admin" -p 'P#ssword' -accepteula cmd /c " HostName >> C:\Users\javed\Desktop\New\Script.log"
} else {
"$computer is not online" >> C:\Users\javed\Desktop\New\Script.log
}
}
Output :
PS C:\Users\javed> C:\Users\javed\Desktop\New\Change-NetworkRoute.ps1
PsExec v2.2 - Execute processes remotely
Copyright (C) 2001-2016 Mark Russinovich
Sysinternals - www.sysinternals.com
psexec.exe : The handle is invalid.
At C:\Users\javed\Desktop\New\Change-NetworkRoute.ps1:26 char:9
+ & C:\Users\javed\Downloads\PsTools\psexec.exe \\$($entry.Name) -u "$(
...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (The handle is invalid.:String) [], Re
moteException
+ FullyQualifiedErrorId : NativeCommandError
Connecting to 10.10.10.100...Couldn't access 10.10.10.100:
Connecting to 10.10.10.100...
PS C:\Users\javed>
Apparently your command line isn't completely evaluated, note that PSExec shows \\$($entry.Name) in the error rather then the actual name.
The correct way to troubleshoot this is to put the first put the command is a variable, show the variable, and then execute it:
$CommandLine = "C:\Users\javed\Downloads\PsTools\psexec.exe \\$($entry.Name) -u ..."
Write-Host $CommandLine # Confirm that this is the command line you expect
if (test-Connection -Cn $($entry.Name) -quiet) {
&$CommandLine
} else {
Anyhow, it is a bad idea to use an external command line as PSExec including credentials to achieve something like this. Instead, I would use WMI to retrieve the actual name of the servers. Something like this:
$SPAdmin = "$($entry.Name)\Admin"
$Password = "P#ssword" | convertto-securestring
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $SPAdmin, $Password
$Computer = Get-WmiObject -Class Win32_Computersystem -ComputerName $entry.Name -Credential $Credential
Write-Host $Computer.Name
The SQL Server service is currently not running.
I am trying to change the password for my local SQL instance then start the instance using PowerShell.
I've tried using a remote session as suggested from this site (http://www.databasejournal.com/features/mssql/managing-sql-server-services-with-powershell.html)
PS - When I run PowerShell ISE 5, I am running it as an admin.
#Create a new remote PowerShell session and pass in the scrip block to be executed
$session = New-PSSession -ComputerName Laptop123 -Credential Domain01\User01
$UserName = "Domain01\User01" # specify user Name here
$Password = "Password1" # specify Password here
Invoke-Command -Session $session -ArgumentList $UserName, $Password -Scriptblock {
param($UserName, $Password)
# Start SQL Server Database engine service (default instance)
$Svc = Get-WmiObject win32_service -filter "name='MSSQL$SQL2008R2_32BIT'"
$Svc.Change($Null, $Null, $Null, $Null, $Null, $Null, $UserName, $Password)
Stop-Service -Name 'MSSQL$SQL2008R2_32BIT' -Force
Start-Service 'MSSQL$SQL2008R2_32BIT'
# Start SQL Server SQL Server Agent service (default instance)
$Svc = Get-WmiObject win32_service -filter "name='SQLAgent$SQL2008R2_32BIT'"
$Svc.Change($Null, $Null, $Null, $Null, $Null, $Null, $UserName, $Password)
Stop-Service -Name 'SQLAgent$SQL2008R2_32BIT' -Force
Start-Service 'SQLAgent$SQL2008R2_32BIT'
}
However, I end up getting the following errors:
Method invocation failed because [System.ServiceProcess.ServiceController] does not contain a method named 'Change'.
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
+ PSComputerName : Laptop123
Service 'SQL Server (SQL2008R2_32BIT) (MSSQL$SQL2008R2_32BIT)' cannot be started due to the following error: Cannot start service MSSQL$SQL2008R2_32BIT on computer '.'.
+ CategoryInfo : OpenError: (System.ServiceProcess.ServiceController:ServiceController) [Start-Service], ServiceCommandException
+ FullyQualifiedErrorId : CouldNotStartService,Microsoft.PowerShell.Commands.StartServiceCommand
+ PSComputerName : Laptop123
Any suggestions on how to change the service password and then start it?
it looks like you are calling the wrong name of the service in your script try changing the name filter to 'SQL Server (SQL2008R2_32BIT)'
Let me know if that works, if not list any output you may receive from trying that.
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..