Remote Exchange Powershell invoke command - customize return result
Hi
I am trying to create a powershell which connects to an exchange management shell and executes a command.
[scriptblock]$Command = {Get-MailboxDatabaseCopyStatus | select Name,ContentIndexState}
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://$Computername/powershell -Credential $Cred
Import-PSSession $Session
$Returnvalue = $Command.Invoke()
Remove-PSSession $Session
This would return a result like this:
Name : DB02 - Specielle\EXCHANGE01
ContentIndexState : Healthy
Name : DB01 - Standard\EXCHANGE01
ContentIndexState : Healthy
Now how do I create an if-sentence that would check if both are "Healthy" and then return "Echo "Healthy"", else if one is not healthy then return "Echo "Not Healthy""? (I dont need to specify which one that
isn't healthy).
Best Regards,
Soren
Hi Soren,
Give this a try (untested, sorry):
[scriptblock]$Command = {
$healthy = $true
$statusList = Get-MailboxDatabaseCopyStatus
foreach ($status in $statusList) {
If ($status.ContentIndexState -ne 'Healthy2') { $healthy = $false }
If ($healthy) { Write-Output 'Healthy' }
Else { Write-Output 'Not Healthy' }
Don't retire TechNet! -
(Don't give up yet - 12,830+ strong and growing)
Similar Messages
-
C# Run VB Script file remotely thriugh PowerShell Invoke Command
I have a requirement where need to run vbscript remotely through PowerShell Invoke command. I can run the VB Script locally but not remotely as the vbscript file is not present on the remote machine. I don't want to copy the script file on remote machine.
Please let me know how to run vb script on remote machine. Below is the code.
Collection<PSObject> output
= null;
using
(Runspace runSpace =
RunspaceFactory.CreateRunspace())
runSpace.Open();
using
(Pipeline pipeline = runSpace.CreatePipeline())
RunspaceInvoke invoke =
new RunspaceInvoke();
PowerShell ps = PowerShell.Create();
ps.Runspace
= runSpace;
ps.AddCommand("invoke-command");
ps.AddParameter("ComputerName",
"RemoteServerName");
ScriptBlock sb = ScriptBlock.Create("cscript E:\\Test\\DeleteFiles.vbs");
ps.AddParameter("ScriptBlock", sb);
output
= ps.Invoke();
Regards, ParveenHello Parveen,
Please refer to the following thread
https://social.msdn.microsoft.com/Forums/vstudio/en-US/7562eefb-7fba-4bf6-834e-82256f159155/run-script-on-remote-macine?forum=csharpgeneral
See his code:
You can use WMI to create processes on a remote machine. In C#, use the ManagementClass.
using System;
using System.Management;
using System.Collections.Generic;
public class MyClass
public static void RunNotepad()
ManagementPath p = new ManagementPath(@"\\targetMachine\root\cimv2:Win32_process");
ManagementClass m = new ManagementClass(p);
m.InvokeMethod("Create", new Object[] {"notepad.exe"});
See: Creating Processes Remotely
Note that the the scrpt file is not executable so you have to create script like this:
cscript.exe "\\yourmachine\script\test.vbs".
Best regards,
Barry
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey. -
How can you run a command with elevated rights on a remote server with invoke-command ?
I am trying to run a script on a remote server with invoke-command. The script is starting and is running fine, but the problem is that it should be running with elevated rights on the remote server. On the server where I start the invoke-command, my account has the necessary rights.
The server were I launch the invoke-command is a W2K8 R2. The remote box is a W2K3 with powershell v2.0 installed.
When I launch the script on the remote-box from the command line, I don't get the access denied's.
Is there a way to do this ?
Thanks in advanceThe script that I want to run is to install the windows updates. I get an access denied on the download of the updates.
When I execute the script on an W2K8 box, (not remotely) and I run it with non-elevated rights, I get the same error.
The script is running fine when it is launched on W2K3 box locally with a domain account that has local admin rights, or on a W2K8 R2 server with a domain account that has local admin rights, but with elevated rights.
Thanks in advance for your help.
#=== start script ====
param($installOption="TESTINSTALL",$rebootOption="NOREBOOT")
Function Show-Help
Write-Host ""
Write-Host "SCRIPT: $scriptName <installOption> <RebootOption>"
Write-Host ""
Write-Host "DESCRIPTION: Installatie van WSUS updates op de lokale server"
Write-Host ""
Write-Host "PARAMETERS"
Write-Host " -installOption <[INSTALL|TESTINSTALL]>"
Write-Host " -rebootOption <[REBOOT|NOREBOOT|REBOOT_IF_UPDATED]>"
Write-Host ""
Write-Host "EXAMPLE:"
Write-Host "$ScriptName -installOption INSTALL -rebootOption REBOOT_IF_UPDATED"
Write-Host "$ScriptNAme INSTALL NOREBOOT"
Write-Host ""
Write-Host "Indien beide parameter weggelaten worden zijn de defaultwaarden :"
Write-Host " installOption=TESTINSTALL "
Write-Host " RebootOption=NOREBOOT"
Write-Host ""
Exit
#Include alle globale variablen
$CEIF_WIN_PATH = (get-content env:CEIF_WIN_PATH)
$includeFile=$CEIF_WIN_PATH + "\Scripts\include_win.ps1"
. $includeFile
#initialiseer error count
$errcnt=0
$scriptName=$MyInvocation.MyCommand.Name
#argumenten controleren
$arrInstallOption= "TESTINSTALL", "INSTALL" # Mandatory variable with predefined values
If (!($arrInstallOption –contains $installOption)){ Show-Help }
$arrRebootOption = "REBOOT", "NOREBOOT","REBOOT_IF_UPDATED" # Mandatory variable with predefined values
If (!($arrRebootOption –contains $rebootOption)){ Show-Help }
#Logfile opbouwen
$logfile = get-logfileName($MyInvocation.MyCommand.Name)
Log-scriptStart $MyInvocation.MyCommand.Name $logfile
function Get-WIAStatusValue($value)
switch -exact ($value)
0 {"NotStarted"}
1 {"InProgress"}
2 {"Succeeded"}
3 {"SucceededWithErrors"}
4 {"Failed"}
5 {"Aborted"}
function boot-server()
if ($installOption -eq "TESTINSTALL")
logger "TESTINSTALL : - Reboot local Server" $logfile
else
logger " - Reboot local Server" $logfile
$thisServer = gwmi win32_operatingsystem
$thisServer.psbase.Scope.Options.EnablePrivileges = $true
$thisServer.Reboot()
$logmsg="Install option = " + $installOption + ", RebootOption = $rebootOption"
logger "$logmsg" $logfile
logger "" $logfile
logger " - Creating WU COM object" $logfile
$UpdateSession = New-Object -ComObject Microsoft.Update.Session
$UpdateSearcher = $UpdateSession.CreateUpdateSearcher()
logger " - Searching for Updates" $logfile
$SearchResult = $UpdateSearcher.Search("IsAssigned=1 and IsHidden=0 and IsInstalled=0")
logger " - Found [$($SearchResult.Updates.count)] Updates to Download and install" $logfile
$Updates=$($SearchResult.Updates.count)
logger "" $logfile
foreach($Update in $SearchResult.Updates)
if ($Update.EulaAccepted -eq 0)
$Update.AcceptEula()
# Add Update to Collection
$UpdatesCollection = New-Object -ComObject Microsoft.Update.UpdateColl
$UpdatesCollection.Add($Update) | out-null
if ($installOption -eq "TESTINSTALL")
else
# Download
logger " + Downloading Update $($Update.Title)" $logfile
$UpdatesDownloader = $UpdateSession.CreateUpdateDownloader()
$UpdatesDownloader.Updates = $UpdatesCollection
$DownloadResult = $UpdatesDownloader.Download()
$Message = " - Download {0}" -f (Get-WIAStatusValue $DownloadResult.ResultCode)
if ($DownloadResult.ResultCode -eq 4 )
{ $errcnt = 1 }
logger $message $logfile
# Install
logger " - Installing Update" $logfile
$UpdatesInstaller = $UpdateSession.CreateUpdateInstaller()
$UpdatesInstaller.Updates = $UpdatesCollection
$InstallResult = $UpdatesInstaller.Install()
$Message = " - Install {0}" -f (Get-WIAStatusValue $InstallResult.ResultCode)
if ($InstallResult.ResultCode -eq 4 )
{ $errcnt = 1 }
logger $message $logfile
logger "" $logfile
#Indien er een fout gebeurde tijdens download/installatie -> stuur mail naar windowsteam
if ( $errcnt -gt 0 )
logger " - Fout tijdens de uitvoering van script -> send mail" $logfile
$mailSubject=$MyInvocation.MyCommand.Name
$msg = new-object Net.Mail.MailMessage
$att = new-object Net.Mail.Attachment($logfile)
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = $mailFrom
$msg.To.Add($mailTo)
$msg.Subject = $mailSubject
$msg.Body = “Meer details in attachement”
$msg.Attachments.Add($att)
$smtp.Send($msg)
#Moet de server herstart worden ?
if ($rebootOption -eq "REBOOT_IF_UPDATED" )
if ($Updates -gt 0)
#Reboot the server when updates are installed
boot-server
elseif ($rebootOption -eq "REBOOT")
#reboot the server always
boot-server
else
#Do not reboot the server
logger "Do not reboot the server" $logfile
Log-scriptEnd $MyInvocation.MyCommand.Name $logfile
exit 0 -
Suppress file deletion confirmation on remote server in Invoke-Command
Hi!
I try create function used for removing folders (and all content) on remote servers .
$FullPathToDelete="\\"+("$Computername\$BasePath\$FolderToDelete").Replace("\\","\")
if (Test-Path $FullPathToDelete -pathType container ) {
$ScriptBlockContent = {
paramater($FullPathToDeleteLocal)
Get-ChildItem -Path $FullPathToDeleteLocal -Recurse | Remove-Item -Force $true -Recurse $true -Confirm:$false | Out-Null
Invoke-Command -Computername $Computername -ScriptBlock $ScriptBlockContent -ArgumentList $FullPathToDelete -AsJob
Remove-Item -Path $FullPathToDelete -Force | Out-Null
Example values for variables
$Computername = "SPPL09281"$BasePath="D$"$FolderToDelete="FolderName"
All work but for every computer (I use this code in a loop) I receive additional prompt for confirmation
Id Name State HasMoreData Location Command
11 Job11 Running True SPPL09281 ...Confirm
The item at Microsoft.PowerShell.Core\FileSystem::\\SPPL09281\D$\FolderName has children and the Recurse
parameter was not specified. If you continue, all children will be removed with the item. Are you sure you want to
continue?
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):
How I can avoid these confirmation prompts?
Thank you in advance.
Wojciech SciesinskiHi Wojciech,
In addition, The original confirm is reminding the folder you want to delete has subfiles, please try to add -recurse parameter:
$FullPathToDelete="\\"+("$Computername\$BasePath\$FolderToDelete").Replace("\\","\")
if (Test-Path $FullPathToDelete -pathType container ) {
$ScriptBlockContent = {
paramater($FullPathToDeleteLocal)
Get-ChildItem -Path $FullPathToDeleteLocal -Recurse | Remove-Item -Force -Recurse -Confirm:$false | Out-Null
Invoke-Command -Computername $Computername -ScriptBlock $ScriptBlockContent -ArgumentList $FullPathToDelete -AsJob
Remove-Item -Path $FullPathToDelete -Recurse -Force
If there is anything else regarding this issue, please feel free to post back.
If you have any feedback on our support, please click here.
Best Regards,
Anna Wang
TechNet Community Support -
Powershell - Invoke-Command Network Connection has been interrupted
Hi,
I have been having this problem intermittently, i use
invoke-command -AsJob -computername myserver1 -scriptblock {get-process}
WARNING: The network connection to myserver1 has been interrupted. Attempting to reconnect for up
to 4 minutes...
WARNING: Attempting to reconnect to myserver1 ...
WARNING: The network connection to myserver1 has
been restored.
On another window i did a ping myserver1 -t to see if any network packets are lost but anything of that sort happened.
I tried using the IP of myserver1 as well and see the same.
Any idea why this message comes up and under what circumstances?
Thanks for your thoughts and help.Hi Past,
this sounds like a temporary lack of access to the necessary remote resources. Direct network connectivity is of course mandatory, but there are more dependencies. Pinging will still work when the WinRM service hangs, local Powershell Execution on the target
is on hold, massive lack of available resources, etc..
I do not know of any specifically typical reasons for this to occur, so the only recommendation I can give you is to do some more in depth monitoring on the target device while recreating the issue.
Cheers,
Fred
There's no place like 127.0.0.1 -
Installing SQL Server 2012 remotely via Powershell using Invoke-Command
I am trying to perform a SQL Server 2012 command line installation using Powershell Invoke-Command on Windows 2012 Datacenter.
The code I am using is as follows:
$ret = Invoke-Command -ComputerName $COMPUTER -ArgumentList $MEDIA,$ACTION,$FEATURES,$INSTALLDIR,$INSTANCEID,$INSTANCENAME,$SQLDATADRIVE,$SQLLOGDRIVE,$DOMAIN,$SQLSERVERSERVICEUSER,$SQLSERVICEPASSWORD,$PRODUCTKEY,$SQLSERVERSA,$username,$ADMINPASSWD
-Credential $cred -ScriptBlock {
param($MEDIA,
$ACTION,
$FEATURES,
$INSTALLDIR,
$INSTANCEID,
$INSTANCENAME,
$SQLDATADRIVE,
$SQLLOGDRIVE,
$DOMAIN,
$SQLSERVERSERVICEUSER,
$SQLSERVICEPASSWORD,
$PRODUCTKEY,
$SQLSERVERSA,
$USERNAME,
$PASSWD)
Set-Location $MEDIA
Import-Module ServerManager
if (-not [IO.Directory]::Exists($MEDIA)){
$hn = hostname
return 0,"Failed to find SQL Server Installer at $MEDIA on $hn"
$tran = ""
Try{
& $MEDIA\setup.exe /ACTION=$ACTION /Q /FEATURES=$FEATURES /IACCEPTSQLSERVERLICENSETERMS /UPDATEENABLED=False /INSTALLSHAREDDIR="$INSTALLDIR\Program Files\Microsoft SQL Server" /INSTALLSHAREDWOWDIR="$INSTALLDIR\Program Files
(x86)\Microsoft SQL Server" /RSINSTALLMODE="FilesOnlyMode" /INSTANCEID="$INSTANCEID" /INSTANCENAME="$INSTANCENAME" /INSTANCEDIR="$INSTALLDIR\Program Files\Microsoft SQL Server" /ENU="True" /AGTSVCSTARTUPTYPE="Automatic"
/SQLSVCSTARTUPTYPE="Automatic" /NPENABLED=1 /TCPENABLED=1 /RSSVCStartupType="Automatic" /ERRORREPORTING=0 /SQMREPORTING=0 /INDICATEPROGRESS /INSTALLSQLDATADIR="$SQLDATADRIVE\DATA" /SQLUSERDBDIR="$SQLDATADRIVE\DATA" /SQLUSERDBLOGDIR="$SQLLOGDRIVE\LOG"
/ASDATADIR="$SQLDATADRIVE\OLAP\DATA" /ASLOGDIR="$SQLLOGDRIVE\OLAP\Log" \ASBACKUPDIR="$SQLDATADRIVE\OLAP\Backup" \ASTEMPDIR="$SQLDATADRIVE\OLAP\Temp" /ASCONFIGDIR="$SQLDATADRIVE\OLAP\Config" /ASCOLLATION="Latin1_General_CI_AS"
/SQLCOLLATION="SQL_Latin1_General_CP1_CS_AS" /SQLSVCACCOUNT="$DOMAIN\$SQLSERVERSERVICEUSER" /SQLSVCPASSWORD="$SQLSERVICEPASSWORD" /AGTSVCACCOUNT="$DOMAIN\$SQLSERVERSERVICEUSER" /AGTSVCPASSWORD="$SQLSERVICEPASSWORD"
/ASSVCACCOUNT="$DOMAIN\$SQLSERVERSERVICEUSER" /ASSVCPASSWORD="$SQLSERVICEPASSWORD" /RSSVCACCOUNT="$DOMAIN\$SQLSERVERSERVICEUSER" /RSSVCPASSWORD="$SQLSERVICEPASSWORD" /FTSVCACCOUNT="NT AUTHORITY\LOCAL SERVICE"
/INDICATEPROGRESS > $out
} Catch [System.Exception] {
return 0,$_.Exception.ToString()
if ($tran -ne ""){
$out += $tran
return 1,$out
The media resides on the server that I am remoting to in powershell and the server is on the same domain. The credentials I pass are for a Domain Admin, but SQL Server fails to validate the credentials for the passed parameter for the sql service user with
a Access Denied.
If I run the same command with the same user directly on the server it works fine.
My guess is that the elavated privs for Administrator are not being set when using Invoke-Command? Is there a way to utilize powershell to install SQL Server 2012 with command line option using the invoke-command and passing credentials? Or is this a limitation
to the SQL Server installer. If there is can a example be provided?Ok, so with the help of some friends, we found a fix that works!
Prior to running the Invoke-Command I now run:
# enable CredSSP on a client computer; this command allows the client credentials to be delegated to the server01 computer.:
Enable-WsManCredSSP -Role Client -DelefateComputer server.some.domain.com
Then I add the -Authentication option to my Invoke-Command with option Credssp.
The install the works fine. Hope this helpes all. -
Hi,
When we launch the Exchange powershell via command prompt.. with below command:
PowerShell.exe -PSConsoleFile "D:\Program Files\Microsoft\Exchange Server\V14\Bin\ExShell.psc1"
it throws the following error:-
Following errors occured when loading the console
D:\Program Files\Microsoft\Exchange Server\V14\Bin\ExShell.psc1:
can not load windows powershell snap-in microsoft.exchange.management.powershell.e2010 because of the following error:
no snap-ins have been registered for windows powershell version 2
We are using Exchange server 2010 SP3 rollup 5 and EXCHANGE Server 2010 SP01.We see the issue on both the servers
Can you please provide the steps to reslove the issue.
Thanks & Regards,
Sanjeev GuptaI have got the resolution of the problem. In my environment, the Powershell.exe which was being launched from command prompt, was 32 bit exe, while it was needed 64 bit exe.
It was occuring because in system path there was 32 bit powershell.exe was present. So, after replacing the exe with 64 bit exe, the problem was solved.
Thanks for the help provided above..
Regards,
Sanjeev -
Exchange Powershell return value from Get-command to variable.
Hi
I am trying to create a powershell-script for our monitoring-software.
The script is supposed to establish a connection to our exchange-server mgmt-shell and execute this command:
"Get-MailboxDatabaseCopyStatus"
I have the connection in place, but am missing the knowledge of how to return the result of the command to my script, which I can then pass to our monitoring-software.
(The script take 2 parameters - host and command eg. exch01.domain and Get-MailboxDatabaseCopyStatus).
Current code:
$statusAlive = "ScriptRes:Host is alive:"
$statusDead = "ScriptRes:No answer:"
$statusUnknown = "ScriptRes:Unknown:"
$statusNotResolved = "ScriptRes:Unknown host:"
$statusOk = "ScriptRes:Ok:"
$statusBad = "ScriptRes:Bad:"
$statusBadContents = "ScriptRes:Bad contents:"
$pass = cat C:\securestring.txt | convertto-securestring
$Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "domain\administrator",$pass
$host = $args[0]
$command = $args[1]
<#
if (!$args[0]) {
echo $statusUnknown"Host parameter is empty"
exit
if (!$args[1]) {
echo $statusUnknown"Command parameter is empty"
exit
#>
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://$host/powershell -Credential $cred
Import-PSSession $session
$command
Remove-PSSession $session
Now, how do I "catch" the value of the executed command and return it to a variable in the script?
Best Regards,
SorenHmm.. doesnt seem to work quite right.
I added "Echo $result" after "Remove-PSSession $session", but then I just get a bunch of information..
Script tmp_c3a1c132-f4d9-4d61... {Get-IRMConfiguration, New-MailUser, Get-PublicFolderMigrationRequestSta...
RunspaceId : 2d179364-2df3-483d-a192-f5f4ca9453bb
Identity : DB02 - Specielle\EXCHANGE01
Id : DB02 - Specielle\EXCHANGE01
Name : DB02 - Specielle\EXCHANGE01
DatabaseName : DB02 - Specielle
Status : Mounted
InstanceStartTime : 01-03-2014 03:35:07
LastStatusTransitionTime :
MailboxServer : EXCHANGE01
ActiveDatabaseCopy : EXCHANGE01
ActiveCopy : True
ActivationPreference : 1
StatusRetrievedTime : 11-03-2014 08:30:15
WorkerProcessId : 8124
ActivationSuspended : False
ActionInitiator : Unknown
ErrorMessage :
ErrorEventId :
ExtendedErrorInfo :
SuspendComment :
RequiredLogsPresent :
SinglePageRestore : 0
ContentIndexState : Healthy
ContentIndexErrorMessage :
ContentIndexVersion : 1
ContentIndexBacklog : 0
ContentIndexRetryQueueSize : 0
ContentIndexMailboxesToCrawl :
ContentIndexSeedingPercent :
ContentIndexSeedingSource :
CopyQueueLength : 0
ReplayQueueLength : 0
ReplaySuspended : False
ResumeBlocked : False
ReseedBlocked : False
MinimumSupportedDatabaseSchemaVersion : 0.121
MaximumSupportedDatabaseSchemaVersion : 0.125
RequestedDatabaseSchemaVersion : 0.125
LatestAvailableLogTime :
LastCopyNotificationedLogTime :
LastCopiedLogTime :
LastInspectedLogTime :
LastReplayedLogTime :
LastLogGenerated : 0
LastLogCopyNotified : 0
LastLogCopied : 0
LastLogInspected : 0
LastLogReplayed : 0
LowestLogPresent : 0
LastLogInfoIsStale : False
LastLogInfoFromCopierTime :
LastLogInfoFromClusterTime :
LastLogInfoFromClusterGen : 0
LogsReplayedSinceInstanceStart : 0
LogsCopiedSinceInstanceStart : 0
LatestFullBackupTime :
LatestIncrementalBackupTime :
LatestDifferentialBackupTime :
LatestCopyBackupTime :
SnapshotBackup :
SnapshotLatestFullBackup :
SnapshotLatestIncrementalBackup :
SnapshotLatestDifferentialBackup :
SnapshotLatestCopyBackup :
LogReplayQueueIncreasing : False
LogCopyQueueIncreasing : False
ReplayLagStatus :
DatabaseSeedStatus :
OutstandingDumpsterRequests : {}
OutgoingConnections :
IncomingLogCopyingNetwork :
SeedingNetwork :
DiskFreeSpacePercent : 50
DiskFreeSpace : 20.02 GB (21,498,761,216 bytes)
DiskTotalSpace : 40 GB (42,946,523,136 bytes)
ExchangeVolumeMountPoint :
DatabaseVolumeMountPoint : E:\
DatabaseVolumeName : \\?\Volume{e6cb407f-e4f2-11e2-93eb-005056ae239d}\
DatabasePathIsOnMountedFolder : False
LogVolumeMountPoint : F:\
LogVolumeName : \\?\Volume{e6cb4087-e4f2-11e2-93eb-005056ae239d}\
LogPathIsOnMountedFolder : False
LastDatabaseVolumeName :
LastDatabaseVolumeNameTransitionTime :
VolumeInfoError :
IsValid : True
ObjectState : Unchanged
RunspaceId : 2d179364-2df3-483d-a192-f5f4ca9453bb
Identity : DB01 - Standard\EXCHANGE01
Id : DB01 - Standard\EXCHANGE01
Name : DB01 - Standard\EXCHANGE01
DatabaseName : DB01 - Standard
Status : Mounted
InstanceStartTime : 01-03-2014 03:35:07
LastStatusTransitionTime :
MailboxServer : EXCHANGE01
ActiveDatabaseCopy : EXCHANGE01
ActiveCopy : True
ActivationPreference : 1
StatusRetrievedTime : 11-03-2014 08:30:15
WorkerProcessId : 8140
ActivationSuspended : False
ActionInitiator : Unknown
ErrorMessage :
ErrorEventId :
ExtendedErrorInfo :
SuspendComment :
RequiredLogsPresent :
SinglePageRestore : 0
ContentIndexState : Healthy
ContentIndexErrorMessage :
ContentIndexVersion : 1
ContentIndexBacklog : 3
ContentIndexRetryQueueSize : 0
ContentIndexMailboxesToCrawl :
ContentIndexSeedingPercent :
ContentIndexSeedingSource :
CopyQueueLength : 0
ReplayQueueLength : 0
ReplaySuspended : False
ResumeBlocked : False
ReseedBlocked : False
MinimumSupportedDatabaseSchemaVersion : 0.121
MaximumSupportedDatabaseSchemaVersion : 0.125
RequestedDatabaseSchemaVersion : 0.125
LatestAvailableLogTime :
LastCopyNotificationedLogTime :
LastCopiedLogTime :
LastInspectedLogTime :
LastReplayedLogTime :
LastLogGenerated : 0
LastLogCopyNotified : 0
LastLogCopied : 0
LastLogInspected : 0
LastLogReplayed : 0
LowestLogPresent : 0
LastLogInfoIsStale : False
LastLogInfoFromCopierTime :
LastLogInfoFromClusterTime :
LastLogInfoFromClusterGen : 0
LogsReplayedSinceInstanceStart : 0
LogsCopiedSinceInstanceStart : 0
LatestFullBackupTime :
LatestIncrementalBackupTime :
LatestDifferentialBackupTime :
LatestCopyBackupTime :
SnapshotBackup :
SnapshotLatestFullBackup :
SnapshotLatestIncrementalBackup :
SnapshotLatestDifferentialBackup :
SnapshotLatestCopyBackup :
LogReplayQueueIncreasing : False
LogCopyQueueIncreasing : False
ReplayLagStatus :
DatabaseSeedStatus :
OutstandingDumpsterRequests : {}
OutgoingConnections :
IncomingLogCopyingNetwork :
SeedingNetwork :
DiskFreeSpacePercent : 50
DiskFreeSpace : 20.02 GB (21,498,761,216 bytes)
DiskTotalSpace : 40 GB (42,946,523,136 bytes)
ExchangeVolumeMountPoint :
DatabaseVolumeMountPoint : E:\
DatabaseVolumeName : \\?\Volume{e6cb407f-e4f2-11e2-93eb-005056ae239d}\
DatabasePathIsOnMountedFolder : False
LogVolumeMountPoint : F:\
LogVolumeName : \\?\Volume{e6cb4087-e4f2-11e2-93eb-005056ae239d}\
LogPathIsOnMountedFolder : False
LastDatabaseVolumeName :
LastDatabaseVolumeNameTransitionTime :
VolumeInfoError :
IsValid : True
ObjectState : Unchanged
I am only interested in the 2 "ContentIndexState" - how can I pick these 2 out and put them into a variable?
I though the command "Get-MailboxDatabaseCopyStatus" would only display these two, since it is what happens if I run the command inside PowerShell on the server itself. -
Certreq -submit run locally returns successful but run remote via invoke-command hangs
Good morning I have been struggling with a certificate request script.
The requesting server is in the dmz and I have a management server internally.
I successfully create the Inf file, as well as the req file then copy the req file to my internal management server. Once copied internal I attempt to run the following command from my laptop executing as my admin account
$Fqdn = "server.dmz.com"
$managementServer = "InternalServer"
$Path = "C$\Test\CertRequests"
Invoke-Command -ComputerName $Managementserver -ScriptBlock {param($CertificateAuthority,$FQDN,$Managementserver,$Path) certreq.exe -submit -attrib "CertificateTemplate:DVNOfflineComputer" -config "$CertificateAuthority" "\\$Managementserver\$Path\$FQDN.req" "\\$Managementserver\$Path\$FQDN.crt"} -ArgumentList $CertificateAuthority,$FQDN,$Managementserver,$Path
This exact command pasted into a powershell window locally on the management server returns the crt file.
Run via invoke-command just hangs forever. I even tried to the Silent=True in inf file as well as -q but neither worked.
Any help is greatly appreciated.Hi Jason,
I reform the script as below, and add the "test-path" to check if the .req and .crt files exist, please also note you haven't assign value to the "$CertificateAuthority" variable:
$Fqdn = "server.dmz.com"
$managementServer = "InternalServer"
$Path = "C$\Test\CertRequests"
$CertificateAuthority = "something"
$script={
param($CertificateAuthority,$FQDN,$Managementserver,$Path)
test-path "\\$Managementserver\$Path\$FQDN.req"
test-path "\\$Managementserver\$Path\$FQDN.crt"
certreq.exe -submit -attrib "CertificateTemplate:DVNOfflineComputer" -config $CertificateAuthority "\\$Managementserver\$Path\$FQDN.req" "\\$Managementserver\$Path\$FQDN.crt"
Invoke-Command -ComputerName $Managementserver -ScriptBlock $script -ArgumentList $CertificateAuthority,$FQDN,$Managementserver,$Path
If there is anything else regarding this issue, please feel free to post back.
Best Regards,
Anna Wang
Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Support, contact [email protected] -
Cannot load Exchange Online Protection commands in Remote PowerShell
My colleagues and I cannot load the Exchange Online Protection commands in Remote PowerShell.
It just loads the Exchange Online cmdlets.
Where are we going wrong?
PS C:\Users\jmorrison> $UserCredential = Get-Credential
cmdlet Get-Credential at command pipeline position 1
Supply values for the following parameters:
PS C:\Users\jmorrison> $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.protection.outlook.com/powershell-liveid/
-Credential $UserCredential -Authentication Basic -AllowRedirection
WARNING: Your connection has been redirected to the following URI: "https://outlook.office
365.com/powershell-liveid?PSVersion=4.0&realm={I've removed my domain name for security reasons}.co.uk "
PS C:\Users\jmorrison> Import-PSSession $Session
ModuleType Version
Name
ExportedCommands
Script
1.0 tmp_4fnmyflw.she
{Add-AvailabilityAddressSpac...
PS C:\Users\jmorrison> Get-TransportRule
Get-TransportRule : The term 'Get-TransportRule' is not recognized as the name of a
cmdlet, function, script file, or operable program. Check the spelling of the name, or
if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ Get-TransportRule
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo
: ObjectNotFound: (Get-TransportRule:String) [], CommandNotF
oundException
+ FullyQualifiedErrorId : CommandNotFoundExceptionI've moved MX records to EOP and seems to be fine all domain expect few.<o:p></o:p>
I can see that problematic domain has "-" between domain names.<o:p></o:p>
mydomain.com<o:p></o:p>
mydomain-com.mail.protection.outlook.com --> has no problem, however<o:p></o:p>
mydomain.usa.com<o:p></o:p>
mydomain-usa-com.mail.protection.outlook.com having issue <o:p></o:p>
when i checked in mx lookup it says MX record has NO A Record.<o:p></o:p>
any suggestions<o:p></o:p> -
Invoking Powershell modules on remote clients via package/command line
Hello Everyone -
I have two modules(functions) that i've written and tested successfully locally in my environment that give me Uninstall and Repair functionality on whatever the string contains. Both .psm1's are delivered via a SCCM pkg that lands both into folders
in the Modules directory. My issue is I can't seem to invoke this in a deployment scenario...as i'd like to deliver the "Invoke-command" using SCCM's command line to simply say...
Invoke-Command -scriptblock { Do-This "<string>" }
The above command works fine locally when...(exePol is set to Bypass).
1.)Modules have respective folders living in WindowsPowershell\Modules directory named xxxx.psm1
2.)Import-Module -name <path\name of module>
3.)Verify Modules are loaded(moduleType is script)
But when fabricating the folders\files above with SCCM, and running the Invoke-Command(in many different ways remotely), i recieve the cmdlet, program doesn't exist and has no idea what i'm talking about. Folders\Files for .psm1's are present and do
show when running Get-Module -Listavailable locally on targeted clients.
Maybe this is related to the Import-Module command and the context i'm trying to delivery it in?
I've tried multiple scenario's of...
A.) Psexec that launches powershell, followed by the Import-Module -name <path\name of module>
B.) .Bat file that launches powershell with the same Import-Module syntax
C.) PS1 that includes the same Import-Module line.
D.) Just straight from the command line of the Pkg/Program.
Has anyone tried this? Is there a better method when trying to deliver invoke-command on a module/function to a client via SCCM?
TIA[I see that the you are running the powershell.exe and then importing the module in the command line for the Program you created in SCCM, so just importing the module will do the repair action for you ??]
Not sure how else i would run a Import-Module without calling upon powershell.exe. The reason for using Import-Module first is it only creates the abilty of whatever the module(function in this case) on the client. So if i can get the remote
Import-Module to work, which would then allow me in the future to use an Invoke-Command -scriptblock { Do-This "string" } on the clients. In this case its both an Uninstall and Repair function with an assortment of switches and arguements that will aide me
in the future in managing our apps. For me to use the Modules, i would need to Invoke-Command as that is how the functions are built.
Okey so the module does get dumped to the end machine.
Suppose you have a test machine TEST01 where the Test.psm1 file (having Test-Function)is delivered through SCCM.
Then try this and tell if it works:
PS C:\> $session = New-PSSession -ComputerName TEST01
PS C:\> Invoke-Command -Session $session -ScriptBlock {Import-Module Test.psm1 }
PS C:\> Invoke-Command -Session $session -ScriptBlock {Test-Function #inside your Module}#Or Simply try below:
PS C:\> Invoke-Command -ComputerName TEST01 -ScriptBlock {Import-Modules Test.psm1;Test-Function #inside your Module}
I think what you are doing is below.....for the example am taking "webadministration" module:
PS C:\> Invoke-Command -ComputerName Server01 -ScriptBlock {Import-Module web*}
PS C:\> Invoke-Command -ComputerName Server01 -ScriptBlock {get-website}
The term 'get-website' is not recognized as the name of a cmdlet, function, script file, or operable program. Check
the spelling of the name, or if a path was included, verify that the path is correct and try again.
+ CategoryInfo : ObjectNotFound: (get-website:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
+ PSComputerName : sdwuweb017
Point here is you need to import the module and work with it in an already opened session....If you specify a computername every time then PowerShell opens the Session does what you want it to do and tears down the session. To persist the importing of the
module it must be done in a session which we make using New-PSSession and then run the commands against that session.
I might have misunderstood the problem but this is what I have got so far.
Hope this helps
Knowledge is Power{Shell}. -
How to run powershell in adminsitrator mode using invoke-command
Hi,
I'm trying to run the below script from the remote machine I'm getting the output as below and the msnpatch.exe is not getting executed on the remote machine(testserver).
When I run the same command on the testserver, a new powershell session is getting opened and able to run msnpatch.exe.
So, how to invoke powershell in runas administrator mode and run msnpatch.exe on that administrator window is my question.
Thanks for your time. Your reply is highly appreciated.
Script:
Invoke-Command -ComputerName testserver -ScriptBlock {
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
$newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
$newProcess.Verb = "runas"
$newProcess.Arguments="-noprofile -command msnpatch.exe"
[System.Diagnostics.Process]::Start($newProcess)
Output:
PS C:\Users\v-sridal> Invoke-Command -ComputerName 1f4-00073 -ScriptBlock{
>> $myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
>> $myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
>> $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
>> $newProcess.Verb = "runas"
>> $newProcess.CreateNoWindow = "true"
>> $newProcess.Arguments="-noprofile -command msnpatch.exe"
>> [System.Diagnostics.Process]::Start($newProcess)
>> }
>>
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
PSComputerName
4 4 244 1156 8 0.06 4968 powershell
testserverThere is no elevation when running remotely. UAC only affects local sessions. You cannot elevate a remote session.
¯\_(ツ)_/¯ -
Hello,
In my code I am trying to start a windows service on an Azure VM via Azure Automation. My code fragment is:
$vm = Get-AzureVM -Name $VMName -ServiceName $VMServiceName
$uri = Get-AzureWinRMUri -ServiceName $vm.ServiceName -Name $vm.Name
# Run a command on the Azure VM
$PSCommandResult = InlineScript {
$options = New-PSSessionOption -SkipCACheck
$output = Invoke-Command -ConnectionUri $Using:uri `
-Credential $Using:Credential `
-SessionOption $options `
-ScriptBlock { stop-service -DisplayName <ServiceName> -Force }
My issue is: Is it possible to pass in a multiple line PS block as the ScriptBlock option?
After looking around online, there appeared to be two options:
$psblock = {
line1
line2
line3
Or
$PSCommand = @"
Line1
Line2
Line3
But I have not been able to get either of these to work. (I was trying to end up with something like below)
$output = Invoke-Command -ConnectionUri $Using:uri `
-Credential $Using:Credential `
-SessionOption $options `
-ScriptBlock { $psCommand }
Can someone offer a suggestion? Putting a few lines of PS code directly into the ScriptBlock parameter does work but it looks ugly!
Thanks!Thanks for getting back to me!
I have tried as you suggested but when I attempt to publish the runbook I get this error:
Runbook definition is invalid. Cannot store the results of this type of expression into a variable. Only the results of commands, pipelines, constant expressions, foreach statements, parallel and sequence statements can be stored in variables.
However if I just cut and paste the same code inside the ScriptBlock { CODE HERE } it works.
Perhaps I am breaking the rule as listed above in bold? Would variable declarations in the code block not be allowed? -
Hi I am a PS virgin so be gentle with me. I am trying to run the vssadmin list writers command on 8 servers.
invoke-command -computername srv-bx-hvc1, srv-bx-hvc2, srv-bx-hvc3, srv-bx-hvc4,
srv-bx-hvc5,
srv-bx-hvc6,
srv-bx-hvc7, srv-bx-hvc8
-command {vssadmin list writers}
The command works but I cannot tell which response is from what server.
The objective whould be to eventually have the command so I know which server has failed vss writers if possible restart them automatically.
Any thoughts on how to achieve this lofty ideal??
ThanksThis is a tweak to the example that JRV listed. I am using this code to just pull the information about the Exchange Writers but you could adapt it for others.
$servers='sdcexmail001','sdcexmail002','sdcexmail003','sdcexmail004','sdcexmail005'
$servers | %{
$sb={
$writers=vssadmin list writers
New-Object PSObject -Property @{Server=$_;Writers=$writers}
$ServerName = $_
$out = invoke-command -computername $_ -scriptblock $sb -Argumentlist $_
$WritersData = $Out.Writers
for ($I = 0;$I -le $WritersData.Count -1;$I++)
$Data = $WritersData[$I]
If($Data.StartsWith('Writer name:'))
$WriterName = ($Data.Split(':')[1]).Trim()
$WriterID = ($WritersData[$I+1].Split(':')[1]).Trim()
$WriterInstID = ($WritersData[$I+2].Split(':')[1]).Trim()
$State = ($WritersData[$I+3].Split(':')[1]).Trim()
$LastError = ($WritersData[$I+4].Split(':')[1]).Trim()
$info = [Ordered]@{
'ComputerName' = "$ServerName";
'WriterName' = "$WriterName";
'WriterID' = "$WriterID";
'WriterInstID' = "$WriterInstID";
'State' = "$State";
'LastError' = "$LastError";
$object = New-Object -TypeName psobject -Property $info
$object | Where-Object {$_.WriterName -like '*Microsoft Exchange*'} | Select-Object -Property ComputerName,WriterName,State,LastError -
Exchange Powershell Commands Missing from EMS
I just performed a fresh install of Exchange 2013 w/ SP1 on Windows 2012 Standard R2 which is also a domain controller in an organization that already has an Exchange 2010 server (on a separate server). When I launch the Exchange Management Shell and attempt
to run "Get-ExchangeServer" I get the error "The term 'Get-ExchangeServer' is not recognized as the name of a cmdlet, function, script file, or operable program..." I see that \\HKLM\SOFTWARE\Microsoft\PowerShell\1\PowerShellSnapIns\Microsoft.Exchange.Management.PowerShell.SnapIn
is loading the module name "D:\Program Files\Microsoft\Exchange\bin\Microsoft.Exchange.PowerShell.Configuration.dll" (which is the correct path to that file).
I've restarted the server twice and have the same issue. Also tried doing an unattended install of just the Managment Tools since using the setup GUI didn't give me the option of uninstalling and reinstalling the Management Tools since the checkbox is greyed
out. I searched the ExchangeSetup log for errors and didn't find any.
How do I get the Exchange Management Shell to register the Exchange Powershell commands? Do I need to uninstall Exchange and Re-Install?Open Powershell as Administrator.
1. Add-Pssnapin *Setup*
2. Install-CannedRbacRoleAssignments -InvocationMode Install -verbose
3. Install-CannedRbacRoleAssignmentSRAP -InvocationMode Install -verbose
4. Install-CannedRbacRoles -InvocationMode Install -verbose
Try the above commands and let me know if that helps
if that doesn't can you run the below command reply back with the output
Get-Command |?{$_.Name -like "Get-Exchange*"}
***VOTE IF HELPFUL / MARK ANSWER IF ANSWERS ***
Pavan Maganti ~ ( Exchange | 2003/2007/2010/E15(2013)) ~~ Please remember to click “Vote As Helpful" if it really helps and "Mark as Answer” if it answers your question, “Unmark as Answer” if a marked post does not actually answer your
question. ~~ This Information is provided is "AS IS" and confers NO Rights!!
Maybe you are looking for
-
How to delete the material records related to storage type
Dear SAP guru's, I got a situation that if the material "XXXXXX" exists in two different storage type (let say 001 & 002 ) and the material needs to be removed out of one (Let say 002) to avoid the picking and putaway in future. Inorder to accomplish
-
Hi, I have a classpath problem with my EAR archive and strange effects. I pack an EAR archive wich contains : - 1 jar containings EJB's - 1 war that use struts - several jars with common objects (DTO) - several jars like common-logging,... + struts j
-
Test cases runs correctly on IDE but fails on the test runner
Hi Guys, I have a test case here that works fine on my Mars IDE with RCPTT but fails when I run it via the Maven plugin on the same machine. The summary of the test case here is that it auto-generates some java files based on changes done to a DSL ty
-
Ask about how to append text on next line
I'm writing lingo about log file. For example, i would like to write like this when a new entry is appended: etc 3/29/2007 8:34 PM etc2 3/29/2007 8:34 PM Here is the lingo: on mouseUp if objectP(myFile) then set myFile = 0 -- Delete the instance if i
-
Just bought the new iphone4s how to i put all my info on to it from my old iphone 4?
just bought an iphone4s how do i put all my info and contacts from my old iphone to my new one?