Invoke-Command Get-Counter

Hi
I'm trying to run some code on remote computers that use get-counter. But the problem is when the data is returned the CounterSamples is not as expected and the data is just:
Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSample
What am i doing wrong?

True :)
When i run this:
$data = get-counter "\Memory\Available kbytes"
$data.CounterSamples
I get this:
Path                                    InstanceName                                
                       CookedValue
\\hyp20\memory\available kbytes                                                                  
             52592044
When i run this:
$data1 = invoke-command -computername hyp20 -scriptblock {get-counter "\Memory\Available kbytes"}
$data1.CounterSamples
I get this:
Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSample
Do you need to use the results for some further use? If not, what happens when change the Invoke-Command line to:
Invoke-Command -ComputerName hyp20 -scriptblock {
$data = Get-Counter "\Memory\Availabile kbytes"
$data.CounterSamples
Jason Warren
@jaspnwarren
jasonwarren.ca
habaneroconsulting.com/Insights

Similar Messages

  • Run invoke-command on multiple machines at the same time

    Hey all so I read that if I store my New-pssession in a variable then used that in my invoke-command it would run all computers at the same time.
    $a = Get-Content "C:\Users\cody-horton\Desktop\list.txt"
    $session
    for($i=0;$i -lt $a.Length;$i++){
    if(!(Test-Connection -Cn $a[$i] -BufferSize 16 -Count 1 -ea 0 -quiet)){
    Write-Host $a[$i] -foregroundcolor red
    else{
    $session = New-PSSession $a[$i]
    Invoke-Command -Session $session -FilePath "\\My computer\C`$\Users\public\Documents\zip folder.ps1"
    What exactly am I doing wrong I just need to run this script on multiple machines at the same time.
    Thanks.
    Edit: Also what would be the best way to close all the sessions thanks.

    Hi there,
    So what I think you are doing wrong here is that you are overwriting the value in $Session everytime you executed code inside for loop. try the below:
    $a = Get-Content "C:\Users\cody-horton\Desktop\list.txt"
    $session = @() #define this as an array
    for($i=0;$i -lt $a.Length;$i++){
    if(!(Test-Connection -Cn $a[$i] -BufferSize 16 -Count 1 -ea 0 -quiet)){
    Write-Host $a[$i] -foregroundcolor red
    else{
    $session += New-PSSession $a[$i] #add the new session to the array, at the end it will be a collection of sessions
    Invoke-Command -Session $session -FilePath "\\My computer\C`$\Users\public\Documents\zip folder.ps1" #I think the above one won't work..first you need to copy the script locally on the machine and then execute it#Why this won't work because of Second-Hop Authentication
    Have put comments where I edited your code.
    Hope this helps
    Knowledge is Power{Shell}. http://dexterposh.blogspot.com/

  • 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 advance

    The 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

  • Get-Counter : The \\ServerNameHere\\SQLSERVER:Locks(_Total)\Lock Waits/sec performance counter path is not valid.

    I have the following code:
    Import-Module "sqlps" -DisableNameChecking
    #####http://www.travisgan.com/2013/03/powershell-and-performance-monitor.html
    function ExtractPerfmonData 
        param(
            [string]$server,
            [string]$instance
        [Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSampleSet]$collections
        $monitorServer = "MonitoringServerNameHere"
        $monitorDB = "MonitoringDatabaseNameHere"
        $counters = @(
            "\$($instance):Memory Manager\Memory Grants Pending",
            "\$($instance):Memory Manager\Target Server Memory (KB)",
            "\$($instance):Memory Manager\Total Server Memory (KB)",
            "\$($instance):Buffer Manager\Buffer Cache Hit Ratio",
            "\$($instance):Buffer Manager\Checkpoint pages/sec",
            "\$($instance):Buffer Manager\Page Life Expectancy",
            "\$($instance):General Statistics\User Connections",
            "\$($instance):General Statistics\Processes Blocked",
            "\$($instance):Access Methods\Page Splits/sec",
            "\$($instance):SQL Statistics\Batch Requests/sec",
            "\$($instance):SQL Statistics\SQL Compilations/sec",
            "\$($instance):SQL Statistics\SQL Re-Compilations/sec",
            "\$($instance):Locks(_Total)\Lock Waits/sec"
        $collections = Get-Counter -ComputerName $server -Counter $counters -SampleInterval 1 -MaxSamples 1
        $sampling = $collections.CounterSamples | Select-Object -Property TimeStamp, Path, Cookedvalue
        $xmlString = $sampling | ConvertTo-Xml -As String
        $query = "dbo.usp_InsertPerfmonCounters_SQLServer '$xmlString';"
        Invoke-Sqlcmd -ServerInstance $monitorServer -Database $monitorDB -Query $query
    #####ExtractPerfmonData -server "YourRemoteServerName" -instance "MSSQL`$SQLTest"
    ExtractPerfmonData -server "ServerName1Here" -instance "SQLSERVER" 
    ExtractPerfmonData -server "ServerName2Here" -instance "SQLSERVER"
    ExtractPerfmonData -server "ServerName3Here" -instance "MSSQL`$InstanceNameHere"  
    ExtractPerfmonData -server "ServerName4Here" -instance "SQLSERVER" 
    (I have 93 instances listed; here I just gave a sample of 4.)
    For only one instance I get the following error message:
    Get-Counter : The
    \\ServerNameHere2\\SQLSERVER:Locks(_Total)\Lock Waits/sec performance counter path  is not valid.
    All of the instances should have been set up the same, so I am confused as to why this error only occurs on this one instance.  I do not know where to look.  Has anyone ever seen this type of error before?
    lcerni

    Here is the output of the first script:
    CounterSetName                                                                                                                     
    ...       (eliminating non sql server counters here)              
    SQLAgent:Alerts                                                        
    SQLAgent:Jobs                                                          
    SQLAgent:JobSteps                                                        
    SQLAgent:Statistics                                      
    SQLServer:Access Methods                                                                                          
    SQLServer:Availability Replica  SQLServer:Backup Device                                                                                                            
    SQLServer:Batch Resp Statistics                                                                                                    
    SQLServer:Broker Activation                                                                                                        
    SQLServer:Broker Statistics                                                                                                        
    SQLServer:Broker TO Statistics                                                                                                     
    SQLServer:Broker/DBM Transport                                                                                                     
    SQLServer:Buffer Manager                                                                                                           
    SQLServer:Buffer Node                                                                                                              
    SQLServer:Catalog Metadata                                                                                                         
    SQLServer:CLR                                                                                                                      
    SQLServer:Cursor Manager by Type                                                                                                   
    SQLServer:Cursor Manager Total                                                                                                     
    SQLServer:Database Mirroring                                                                                                       
    SQLServer:Database Replica                                                                                                         
    SQLServer:Databases                                                                                                                
    SQLServer:Deprecated Features                                                                                                      
    SQLServer:Exec Statistics                                                                                                          
    SQLServer:FileTable                                                                                                                
    SQLServer:General Statistics                                                                                                       
    SQLServer:Latches                                                                                                                  
    SQLServer:Locks                                                                                                                    
    SQLServer:Memory Broker Clerks                                                                                                     
    SQLServer:Memory Manager                                                                                                           
    SQLServer:Memory Node                                                                                                              
    SQLServer:Plan Cache                                                                                                               
    SQLServer:Query Execution                                                                                                          
    SQLServer:Replication Agents                                                                                                       
    SQLServer:Replication Dist.                                                                                                        
    SQLServer:Replication Logreader                                                                                                    
    SQLServer:Replication Merge                                                                                                        
    SQLServer:Replication Snapshot                                                                                                     
    SQLServer:Resource Pool Stats                                                                                                      
    SQLServer:SQL Errors                                                                                                               
    SQLServer:SQL Statistics                                                                                                           
    SQLServer:Transactions                                                                                                             
    SQLServer:User Settable                                                                                                            
    SQLServer:Wait Statistics                                                                                                          
    SQLServer:Workload Group Stats                                                                                                     
    ...       (eliminating non sql server counters here)
    lcerni

  • Error occurred in deployment step 'Add Solution': A timeout has occurred while invoking commands in SharePoint host process.

    Hi,
    I am deplyoing a  solution which has  custom web parts- vwp- appln pages, event receivers.
    It was working fine till last week. I was able to deploy the solution and able to see the web parts and func. was working.
    But now from the last 2 days onwards, when I tried to depoy this soution, I am getting the error
    "Error occurred in deployment step 'Add Solution': A timeout has occurred while invoking commands in SharePoint host process "
    may i know why am getting this error.
    note: my dev machine- Win Srvr 2012 - VS 2012- SP 2013 - SP D 2013 was having soem issues  with the space in C drive.
    once i have done the  index reset few months back and i started getting space in C:\ Drive is 0 bytes.
    so what my infra. team  has done is , increased the space in drive to 150 GB[ it was a  VM ].
    help is appreciated !

    What is current disk space on your drives
    Delete ULS logs and other log files from server id not needed
    could be related to ChannelOperationTimeout
    http://msdn.microsoft.com/en-us/library/ee471440(v=vs.100).aspx
    Also, don't forget to restart Visual Studio
    Goto the following regustry key: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\SharePointTools
    Add the following as a DWORD (wont be there by default)
    ChannelOperationTimeout
    REG_DWORD that specifies the time, in seconds, that Visual Studio waits for a SharePoint command to execute. If the command does not execute in time, a SharePointConnectionException is thrown.
    The default is 120 seconds.
    http://social.technet.microsoft.com/wiki/contents/articles/21052.como-resolver-o-erro-error-occurred-in-deployment-step-activate-features-a-timeout-has-occurred-while-invoking-commands-in-sharepoint-host-process-pt-br.aspx
    If this helped you resolve your issue, please mark it Answered

  • Error occurred in deployment step 'Activate Features': A timeout has occurred while invoking commands in SharePoint host process.

    Error 1 Error occurred in deployment step 'Activate Features': A timeout has occurred while invoking commands in SharePoint host process.
    0 0 myProjectAssetsLists
    am getting the above error when i deploy my farm solution which is actually a "farm solution import package" template.
    i am deploying this to a new site collection and once its features are activated this will provision few doc libs and splists in the targeted site.
    any help is appreciated.

    try below link:
    http://msdn.microsoft.com/en-us/library/ee471440.aspx
    http://sujeetrec.blogspot.in/2013/12/sharepoint-2010-deployment-timing-out.html
    Increase the timeout that Visual Studio waits for SharePoint to deploy a feature:
    Create: [HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\SharePointTools] ChannelOperationTimeout DWORD
    The value is a timeout in seconds. The default is 120 (2 minutes).
    Full details on this switch and others are here:
    http://msdn.microsoft.com/en-us/library/ee471440.aspx

  • A communication error has occurred while invoking commands in SharePoint host process

    Hi All,
    I am using Virtual box to connect to Sharepoint 2013 VPC. Due to an unexpected sutdown of my machine the VPC got some issue. Now I restored it using my bak up file. But after this when I deploy my sharepoint 2013 farm solution Iam getting the following error.
    Error occurred in deployment step 'Recycle IIS Application Pool': A communication error has occurred while invoking commands in SharePoint host process: The server did not provide a meaningful reply; this might be caused by a contract mismatch, a premature
    session shutdown or an internal server error.
    What could be the issue? Any suggestions ?
    Thanks in advance...
    Regards
    Nimisha
    [email protected]

    Hi Nimisha,
    Seems that the original issue of communication error has been solved, for this new issue, it is recommended that you open a new thread which can make others easier
    to focus on one issue in one single thread.
    Best regards,
    Patrick
    Patrick Liang
    TechNet Community Support

  • 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                    
    testserver

    There is no elevation when running remotely. UAC only affects local sessions. You cannot elevate a remote session.
    ¯\_(ツ)_/¯

  • 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 Sciesinski

    Hi 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

  • Can't get counter 2/3 working in simple event counting mode for NI6601

    I have been successfully been able to get counter 0 and 1 working in a simple event counting mode. But when I read Software Save register for counter2/3 it gives me garbage values. I am doing register level programming in C.
    This is the algorithm that I follow
    In initialization:
    -> Reset the Counter
    -> Write32( Clock_Config_Reg, 0x00)
    -> Write Load A and LoadB registers
    -> Write to Input Select Register with appropriate values
    -> Write16( Command_Reg, 0x0125);
    Then when I need to read the SW save register value
    -> Write to Command Register  setting the  gi_Arm bit
    -> Reading the SW save register twice
    -> If not equal ,read again
    -> Write to Command Register  disabling the  gi_Arm bit
    This works just fine for counter 0 and 1. But I can't get it working for counter 2 and 3. Are there any other registers I need to set up correctly for counter2/3. Is the default reset values of registers different for counter 2 and 3?
    Any help would be very appreciated
    Thanks

    Hello manisha,
    Is there a particular reason for using register level programming to interact with your DAQ card, rather than the DAQmx driver?  The reason I ask is because we don't support RLP at NI.  There are some manuals that have been developed, such as this one which corresponds to your card, but I am unable to offer any support after that.  If it is necessary that you must use RLP then you should post your question to the DDK forum, as they have more experience in this area.
    Regards,

  • Is there a way to make invoke-command interactive?

    Hello,
    I have a script that runs an invoke-command with multiple arguments and performs operation on a remote workstation.
    I want to add some additional confirmations and dialogue choices depending on how the script block executes on the remove PC.
    Is there a way to do that?

    I'm afraid it's not possible in my scenario.
    I'm using invoke-command with Credssp authentication because I need to execute a number of commandlets that are only installed on a specific remote server. Those powershell commandlets from Microsoft do not work if installed on the client.
    Those commandlets use network share resources too, that's why Credssp is used.
    During the execution of invoke-command I wanted to make an additional confirmation for overwriting of some resources.
    The other option is to run several invoke-commands and get output from the queries, construct the dialogue options based on those queries and  gather input locally and then run the final execute invoke-command last, but it seems just like too much of
    hassle for now, so i'll leave things as they are.

  • Is it possible to pass a multi line PowerShell code block to the Invoke-Command ScriptBlock option?

    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?

  • Using invoke-command to run 'vssadmin list writers' on several servers, how do I sort the results from each server?

    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??
    Thanks

    This 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

  • Invoke-command takes 20-90 seconds to complete

    all servers I'm testing with is server 2008r2 with powershell 4.  I have a text file with 100 servers that are online and with PS remoting enabled.
    When I run this command:
    # this takes about 20-30 seconds to complete
    Invoke-Command
    -ScriptBlock
    {get-date}
    -ComputerName
    (gc
    100servers.txt)
    # this takes at least 90 seconds to complete when I set throttle to 100
    Invoke-Command
    -ScriptBlock
    {get-date}
    -ComputerName
    (gc
    100servers.txt)
    -ThrottleLimit
    100
    I didn't get these delays when my local was running powershell 2 and executing against the same set of servers with PS4 on them.  PS2 only took 2-3 seconds to finish the command if all were online.  If I run the command in PS4 ISE, it seems to
    work fast as well but for some reason PS4 traditional shell (not ISE) gives me these delays when working with large set of servers and increasing throttle to 100+
    Sometimes you get different results if you keep running it with the same shell, but if you open a new shell with -noprofile switch then I get the same execution delays with PS4.
    # I even tried skipping the different checks with sessionOption below but same results
    Invoke-Command
    -ScriptBlock
    {get-date}
    -ComputerName
    (gc
    100servers.txt)
    -ThrottleLimit
    100
    -SessionOption
    (New-PSSessionOption
    -SkipCACheck
    -SkipRevocationCheck
    -SkipCNCheck)
    I also tried running the same command from win8.1 with PS4 and it will hang for about 90 seconds before it spits out all the results at once.
    This seems to be a problem with large number of servers of at least 50.  Works fine with small set.  Is anyone else having this problem?  I know there's other ways of running scripts in parallel, but I can't figure out why this is not working. 
    I'm also using the default pssessionoption below.  I have full admin rights to all the servers.  Any suggestions?
    MaximumConnectionRedirectionCount : 5
    NoCompression                     : False
    NoMachineProfile                  : False
    ProxyAccessType                   : None
    ProxyAuthentication               : Negotiate
    ProxyCredential                   :
    SkipCACheck                       : False
    SkipCNCheck                       : False
    SkipRevocationCheck               : False
    OperationTimeout                  : 00:03:00
    NoEncryption                      : False
    UseUTF16                          : False
    IncludePortInSPN                  : False
    OutputBufferingMode               : None
    Culture                           :
    UICulture                         :
    MaximumReceivedDataSizePerCommand :
    MaximumReceivedObjectSize         :
    ApplicationArguments              :
    OpenTimeout                       : 00:03:00
    CancelTimeout                     : 00:01:00
    IdleTimeout                       : -00:00:00.0010000

    -asjob only puts it in the background, but it still takes the same amount of time to finish.  Any other suggestions?  I want to be able to increase the throttle to at least 100 servers.  With PS2, I was able to throttle to 200 servers and
    was very fast.  Not sure why PS4 is so much slower.  It seems to run better without increasing the throttle, but still slower when dealing with 100 servers compared to PS2 results.
    Invoke-Command
    -ScriptBlock
    {get-date}
    -ComputerName
    (gc
    100servers.txt)
    -ThrottleLimit
    100

  • Logging Invoke-Command

    Hello,
    I have a problem with logging on multiple servers at the same time. I would like to have a single file with every log formated like this :
    "yyyyMMdd HH:mm:ss - $Env:ComputerName - result of the command"
    To know what computer is doing what, I am currently logging in separate files on each server running the following code :
    $ExecDate = Get-Date -Format yyyy-MM-dd_HH-mm
    $TroncateLocalLogFileName = "C:\Temp\$ExecDate"
    $ScriptBlock= {
    Param ($TroncateLocalLOgFileName)
    Get-Date
    Echo *****************
    Write-Host "Blablabla is running on" $Env:ComputerName ", please wait..."
    Echo "Blablabla is running, please wait..."
    & "C:\Program Files\firstscript.ps1"
    Echo *****************
    Echo "Enabling BLABLABLA for $env:computername..."
    Set-ItemProperty -Path HKLM:\MyRegistryPath -name MyRegistryKey -Value 1
    Echo *****************
    Echo "End of procedure"
    Write-Host "BALBALBLA for" $env:computername "is done"
    Echo *****************
    Get-Date
    } > $TroncateLocalLOgFileName"_$Env:ComputerName.log" 2>&1
    invoke-command -ComputerName $ListOfServers -ArgumentList $TroncateLocalLogFileName -ScriptBlock $ScriptBlockforeach ($Computer in $ListOfServers) {
    robocopy \\$Computer\$LogSource $LogDestination\ $Execdate"_*" /MOV
    Does anyone knows how to add some string to output inside an Invoke-Command to get the required result ?
    I tried everything I could think of without anything getting near...
    Thanks in advance for your help.

    Hi Pierre,
    If you want to export the result to a single log file instead of mutiple log files located on every remote computers, please try to export the log file outside the scriptblock of the the cmdlet "Invoke-Command", and use the cmdlet "Out-File"
    to append every result from remote computers to a single file:
    $ExecDate = Get-Date -Format yyyy-MM-dd_HH-mm
    $TroncateLocalLogFileName = "C:\Temp\$ExecDate"
    $ScriptBlock= {
    Param ($TroncateLocalLOgFileName)
    Get-Date
    Echo *****************
    Write-Host "Blablabla is running on" $Env:ComputerName ", please wait..."
    Echo "Blablabla is running, please wait..."
    & "C:\Program Files\firstscript.ps1"
    Echo *****************
    Echo "Enabling BLABLABLA for $env:computername..."
    Set-ItemProperty -Path HKLM:\MyRegistryPath -name MyRegistryKey -Value 1
    Echo *****************
    Echo "End of procedure"
    Write-Host "BALBALBLA for" $env:computername "is done"
    Echo *****************
    Get-Date
    invoke-command -ComputerName $ListOfServers -ArgumentList $TroncateLocalLogFileName -ScriptBlock $ScriptBlock | out-file $TroncateLocalLOgFileName"_$Env:ComputerName.log" -append
    If there is anything else regarding this issue, please feel free to post back.
    Best Regards,
    Anna Wang

Maybe you are looking for