Invoke-Command and ShellId Issues

Hi all,
I'm struggling to figure out what is going on here.
I'm trying to add a domain user to a VM's local administrators group via this:
$localAdminBlock = `
$objUser = [ADSI]("WinNT://domain/domainaccount")
$objGroup = [ADSI]("WinNT://$vm/Administrators")
$objGroup.PSBase.Invoke("Add",$objUser.PSBase.Path)
Invoke-Command -ComputerName $vm -Scriptblock $localAdminBlock -Credential $adminCreds
I receive an error:
"Processing data from remote server TestServer failed with the following error message: The request for the Windows Remote Shell with ShellId <id here> failed because the shell was not found on the server.  Possible causes are: the specified
ShellId is incorrect or the shell no longer exists on the server.  Provide the correct ShellId or create a new shell and retry the operation..."
Any idea what's going on?
Thanks.

You need to use $using:vm instead of $vm since you are passing a value from a local variable into the scriptblock which
is executed remotely. If you don't do this then the $vm will be $null in the remote session. If you use $using:vm then Invoke-Command will evaluate the local $vm variable and use this value in the remote session.
$localAdminBlock = `
$objUser = [ADSI]("WinNT://domain/domainaccount")
$objGroup = [ADSI]("WinNT://$using:vm/Administrators")
$objGroup.PSBase.Invoke("Add",$objUser.PSBase.Path)
Invoke-Command -ComputerName $vm -Scriptblock $localAdminBlock -Credential $adminCreds
--Neptune
That was the issue, thanks a lot!

Similar Messages

  • Invoke-Command and $using:ACL problem

    Hi,
    Can anyone point me in the right direction.
    I want to modify and ACL on a remote server, but i cannot assign a variable inside the invoke-command where i'm also refferencing an local variable.
    When the first invoke-command is ran i get an error:
    A Using variable cannot be retrieved. A Using variable can be used only with Invoke-Command, Start-Job, or InlineScript
    in the script workflow. When it is used with Invoke-Command, the Using variable is valid only
    if the script block is invoked on a remote computer.
    $DriveFunctionDirectoryStructure="z:\projects\1"
    Invoke-Command
    -Session$s-ScriptBlock{$acl=get-acl$using:DriveFunctionDirectoryStructure}
    Invoke-Command
    -Session$s-ScriptBlock{$acl.SetAccessRuleProtection($using:True,$using:ToggleAccessRuleFlag)}
    Invoke-Command
    -Session$s-ScriptBlock{Start-Sleep-Seconds5}
    Invoke-Command
    -Session$s-ScriptBlock{$rule=New-ObjectSystem.Security.AccessControl.FileSystemAccessRule("localdomain\$using:groupName","$using:AccessOption","ContainerInherit,
    ObjectInherit","None","Allow")}
    Invoke-Command
    -Session$s-ScriptBlock{$acl.AddAccessRule($rule)}
    Invoke-Command
    -Session$s-ScriptBlock{Set-Acl$using:DriveFunctionDirectoryStructure$acl}

    Hi RFalken,
    you can use the -ArgumentList parameter of Invoke-Command like this:
    $script = {
    Param (
    $Parameter1,
    $Parameter2
    Invoke-Command -ScriptBlock $script -ArgumentList @(2,42)
    Cheers,
    Fred
    There's no place like 127.0.0.1

  • Illustrator CC Command and Saving Issues

    HI,
    My colleagues and I updated to Illustrator CC this week. We were hoping that the upgrade may fix an issue we have(in a seperate thread) and while it hasn't fixed it, it does seem to have created a couple more bugs as follows:
    1. Certain commands such as cut, group/ungroup, zoom etc.. dont seem to work all the time by using the keyboard shortcuts. If I try a command and it doesnt work, I need to scroll the page over using the mouse slightly and then the command seems to work for a few moments. Sometimes I am needing to do this 3 or 4 times in one job which can get quite infuriating.
    2. Sometimes when after openeing a file and adjusting the artwork, it is not giving the option to save(it is grayed out and the keyboard command doesnt work) and the file can only use 'Save As'
    Stangley it doesnt seem to be happening on all our machines, we have 5 Macs running CC and only 2 have the Command Shortcut issues and only 1 seems to have the saving issue
    Has anyone else had either of these issues or are aware of them? If so do you know of a solution or reason to the problems.
    Any input would be greatly appreciated.
    Many thanks

    Martyn,
    It may be a slightly different case of the Missing Verdana and Tahoma issue,
    http://forums.adobe.com/message/5453325#5453325
    http://forums.adobe.com/message/5506635#5506635
    Or you may have a look at other applications mobbing Illy, see Item 7) under Other options; there are a few missing from the list, BetterTouch and anti virus software.

  • 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

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

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

  • Invoke-WSManAction command and CIM Object references

    Hi,
    I am using powershell on my Windows Server 2008 R2 system to invoke a CIM class method that takes a reference object argument. The signature of the method is something like:
    uint32 DoSomething([IN, Description(" Does something ")] CIM_LogicalPort ref Target);
    The command I use to invoke this method is:
    PS C:\Users\Administrator> $list = Get-WSManInstance -Enumerate -ResourceURI "http://schemas.microsoft.com/wbem/wsman/1/wmi/root/****/CIM_FCPort" -ReturnType EPR
    PS C:\Users\Administrator>
    PS C:\Users\Administrator> invoke-wsmanaction -action DoSomething -resourceuri "http://schemas.microsoft.com/wbem/wsman/1/wmi/root/****/CIM_SoftwareInstallationService" -selectorset @{CreationClassName="CIM_SoftwareInstallationService";Name="CIM_SoftwareInstallationService";SystemCreationClassName="CIM_ComputerSystem";SystemName="testServer"}
    -ValueSet @{Target=$($list[0].InnerXml)}
    xsi         : http://www.w3.org/2001/XMLSchema-instance
    p           : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/****/CIM_SoftwareInstallationService
    cim         : http://schemas.dmtf.org/wbem/wscim/1/common
    lang        : en-US
    ReturnValue : 32968
    PS C:\Users\Administrator>
    Though the command execution succeeds, the CIM Provider fails as the reference argument passed in the powershell command reaches the provider as NULL.
    My questions are:
      1. What is the right way to pass the CIM objects by reference to the methods?
      2. Is the syntax of the commands I am using correct?
    Notes:
      - I have tried the same thing with "winrm" and "Invoke-CIMMethod" commands as well, but with the same failure.
      - The same commands seem to have worked for some people in a similar scenario (http://somethingaboutcode.wordpress.com/2009/11/09/invoking-hyper-v-wmi-api-methods-with-reference-parameters-using-ws-management/).
    I really appreciate any help on this.
    Cheers,
    Venu

    Hello AnnaWY,
    First of all, thanks for the reply.
    In fact, that is the link I followed to get my commands and it was very helpful. I think the EPR is reaching the WINRM server as it is supposed to (I have verified it with wireshark capture when executing the command remotely; copy-pasted below), but when
    it reaches the CIM Provider, it is NULL. I suspect one of the below might be happening:
      1. WINRM is not able to get the object from the EPR.
      2. WINRM is passing the argument as NULL when invoking the method.
      3. Something could be going wrong during marshalling (?!!).
    Is there a way to know which one of the above is the case?
    Please note: I have tried enabling the "WMI" and "Windows Remote Management" traces and it didn't help much.
    Thanks again,
    Venu
    REQUEST
    <s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:p="http://schemas.microsoft.com/wbem/wsman/1/wsman.xsd" xmlns:w="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd">
        <s:Header>
            <a:To>http://10.192.203.53:5985/wsman</a:To>
            <w:ResourceURI s:mustUnderstand="true">http://schemas.microsoft.com/wbem/wsman/1/wmi/root/****/CIM_SoftwareInstallationService</w:ResourceURI>
            <a:ReplyTo>
                <a:Address s:mustUnderstand="true">http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address>
            </a:ReplyTo>
            <a:Action s:mustUnderstand="true">http://schemas.microsoft.com/wbem/wsman/1/wmi/root/****/CIM_SoftwareInstallationService/DoSomething</a:Action>
            <w:MaxEnvelopeSize s:mustUnderstand="true">153600</w:MaxEnvelopeSize>
            <a:MessageID>uuid:2A713DC6-F79A-452F-9AA6-D19D9A929C9B</a:MessageID>
            <w:Locale s:mustUnderstand="false" xml:lang="en-US"/>
            <w:OperationTimeout>PT60.000S</w:OperationTimeout>
            <w:SelectorSet>
                <w:Selector Name="CreationClassName">CIM_SoftwareInstallationService</w:Selector>
                <w:Selector Name="Name">CIM_SoftwareInstallationService</w:Selector>
                <w:Selector Name="SystemCreationClassName">CIM_ComputerSystem</w:Selector>
                <w:Selector Name="SystemName">testServer</w:Selector>
            </w:SelectorSet>
        </s:Header>
        <s:Body>
            <p:DoSomething_INPUT xmlns:p="http://schemas.microsoft.com/wbem/wsman/1/wmi/root/****/CIM_SoftwareInstallationService">
                <p:Target>
                    <a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address>
                    <a:ReferenceParameters>
                        <w:ResourceURI>http://schemas.microsoft.com/wbem/wsman/1/wmi/root/****/CIM_FCPort</w:ResourceURI>
                        <w:SelectorSet>
                            <w:Selector Name="CreationClassName">CIM_FCPort</w:Selector>
                            <w:Selector Name="DeviceID">0000ABCDABCD0000</w:Selector>
                            <w:Selector Name="SystemCreationClassName">CIM_ComputerSystem</w:Selector>
                            <w:Selector Name="SystemName">testServer</w:Selector>
                        </w:SelectorSet>
                    </a:ReferenceParameters>
                </p:Target>
            </p:DoSomething_INPUT>
        </s:Body>
    </s:Envelope>
    RESPONSE
    <s:Envelope xml:lang="en-US" xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:x="http://schemas.xmlsoap.org/ws/2004/09/transfer" xmlns:w="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd"
    xmlns:p="http://schemas.microsoft.com/wbem/wsman/1/wsman.xsd">
        <s:Header>
            <a:Action>http://schemas.microsoft.com/wbem/wsman/1/wmi/root/****/CIM_SoftwareInstallationService/DoSomethingResponse</a:Action>
            <a:MessageID>uuid:25561441-A48B-4DDF-B201-BDD00024EC25</a:MessageID>
            <a:To>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:To>
            <a:RelatesTo>uuid:2A713DC6-F79A-452F-9AA6-D19D9A929C9B</a:RelatesTo>
        </s:Header>
        <s:Body>
            <p:DoSomething_OUTPUT xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://schemas.microsoft.com/wbem/wsman/1/wmi/root/****/CIM_SoftwareInstallationService" xmlns:cim="http://schemas.dmtf.org/wbem/wscim/1/common">
                <p:ReturnValue>32968</p:ReturnValue>
            </p:DoSomething_OUTPUT>
        </s:Body>
    </s:Envelope>

  • 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

  • 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

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

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

  • Invoke-Command Set-Item wsman : Access Denied

    Hi,
    I'm trying to write a script that run another script via an Invoke-Command cmdlet. This script is :
    $usrname = "[email protected]"
    $pwd = "MonPassword"
    $pwd = ConvertTo-SecureString -AsPlainText $pwd -Force
    $cred1 = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $usrname, $pwd
    Invoke-Command -ComputerName "SRVFWL" -FilePath "c:\Scripts\VPNScript.ps1" -Credential $cred1
    So this first script run the next script with the user [email protected] :
    $ID = "UserID"
    $RCMPUSR = "UsrOnVpnCmp"
    $RCMPPWD = "MyPass"
    $RCMPPWD = ConvertTo-SecureString -AsPlainText $RCMPPWD -Force
    $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $RCMPUSR, $RCMPPWD
    #Connection to RRAS TMG 2010
    $root = New-Object -ComObject "FPC.Root"
    $isaarray = $root.GetContainingArray()
    $sessionmonitor = $isaarray.SessionsMonitors.SessionsMonitorFirewall
    $filter = New-object -ComObject FPC.FPCFilterExpressions
    #Retreive VPN session
    $sessionmonitor.ExecuteQuery($filter,10000)
    #Check session
    foreach($session in $sessionmonitor)
    if($session.ClientIP.StartsWith("10.10."))
    if($session.ClientUserName -eq "MYDOM\\"+$ID)
    Set-Item wsman:\localhost\client\trustedhosts $session.ClientIP -Force
    If((Test-WSMan $session.ClientIP).IsEmpty -eq $false)
    $CMPName = Invoke-Command -ComputerName $session.ClientIP -ScriptBlock {$(Get-WmiObject Win32_Computersystem).name} -credential $cred
    $Version = Invoke-Command -ComputerName $session.ClientIP -ScriptBlock {[Environment]::OSVersion.Version} -credential $cred
    If($Version.Major -eq 6)
    $sessionmonitor.DisconnectSession("MyTMGServer",$session.SessionID)
    $usr = $ID + "@mydom.pri"
    netsh ras set client $usr disconnect
    return $true
    $sessionmonitor.EndQuery()
    This second script run greatly when I run it manually on the local server connected with the svc_scripts user. But I've a Access Denied on the Set-Item cmdlet of the second script when i try to run it with the Invoke-Command.
    I don't understand why this same user are allowed to run the script locally but not allowed on remote computer.
    Can you help me ?
    Thank you.

    Hi Judicael44,
    First You will encounter the second-hop issue when run "invoke-commmand" as the scriptblock in another remote cmdlet, for more detailed information, please refer to this article:
    Enabling Multihop Remoting
    For the error you posted, Let me restate this issue, we have two servers:
    Local server: server1
    remote server: SRVFWL
    So the second script is located on server1, and the user "[email protected]" has admin right on server
    SRVFWL, you got the error "access denied" when ran the script on remote server SRVFWL.
    In this case, please make sure you have ran the cmdlet "Enable-PSRemoting -Force" on server SRVFWL, which will give you the rights to access and modify TrustedHosts setting in WinRm.
    I tested with single cmdlet, and this could work:
    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

  • Are there any memory restrictions when using Invoke-Command?

    Hi, I'm using the Invoke-PSCommandSample workbook to run a batch file inside a VM.
    The batch file inside the VM runs a Java program.
    The batch file works fine, when I run it manually in the VM.
    However, when I use the Invoke-PSCommandSample workbook to run the batch file, I get the following error:
    Error occurred during initialization of VM
    Could not reserve enough space for object heap
    errorlevel=1
    Press any key to continue . . .
    Does anybody know if there are any memory restrictions when invoking commands inside a VM via runbook?
    Thanks in advance.

    Hi Joe, I'll give some more background information. I'm doing load testing with JMeter in Azure and I want to automate the task. This is my runbook:
    workflow Invoke-JMeter {
    $Cmd = "& 'C:\Program Files (x86)\apache-jmeter-2.11\bin\jmeter-runbook.bat'"
    $Cred = Get-AutomationPSCredential -Name "[email protected]"
    Invoke-PSCommandSample -AzureSubscriptionName "mysubscription" -ServiceName "myservice" -VMName "mymachine" -VMCredentialName "myuser" -PSCommand $Cmd -AzureOrgIdCredential $Cred
    This is my batch file inside the VM:
    set JAVA_HOME=C:\Program Files\Java\jdk1.7.0_71
    set PATH=%JAVA_HOME%\bin;%PATH%
    %COMSPEC% /c "%~dp0jmeter.bat" -n -t build-web-test-plan.jmx -l build-web-test-plan.jtl -j build-web-test-plan.log
    Initially I tried to run JMeter with "-Xms2048m -Xmx2048m". As that didn't work, I lowered the memory allocation but even with "-Xms128m -Xmx128m" it does not work. I have tried with local PowerShell ISE as you suggested, but I'm
    running into certification issues. I'm currently have a look at this. Here's my local script:
    Add-AzureAccount
    Select-AzureSubscription -SubscriptionName "mysubscription"
    $Uri = Get-AzureWinRMUri -ServiceName "myservice" -Name "mymachine"
    $Credential = Get-Credential
    $Cmd = "& 'C:\Program Files (x86)\apache-jmeter-2.11\bin\jmeter-runbook.bat'"
    Invoke-command -ConnectionUri $Uri -credential $Credential -ScriptBlock {
    Invoke-Expression $Args[0]
    } -Args $Cmd
    With this, I get the following error (sorry, it is in German):
    [myservice.cloudapp.net] Beim Verbinden mit dem Remoteserver "myservice.cloudapp.net" ist folgender Fehler
    aufgetreten: Das Serverzertifikat auf dem Zielcomputer (myservice.cloudapp.net:666) enthält die folgenden
    Fehler:
    Das SSL-Zertifikat ist von einer unbekannten Zertifizierungsstelle signiert. Weitere Informationen finden Sie im
    Hilfethema "about_Remote_Troubleshooting".
        + CategoryInfo          : OpenError: (myservice.cloudapp.net:String) [], PSRemotingTransportException
        + FullyQualifiedErrorId : 12175,PSSessionStateBroken

  • Musings: MVC Front Controller/Command and Controller Strategy

    Hi,
    I am currently taking my first shot at implementing the Front Controller pattern, the Command and Controller Strategy flavor, in Java. When applying the pattern, my chosen point of focus is achieving as much isolation as possible of Client-specific implementation details from the rest of the framework (Web-based framework Clients, Swing-based framework Clients, queueing-based framework Clients, etc.) However, I am running into a lot of (apparent?) inconsistencies when it comes to CCS discussions "out there", so I have a feeling that perhaps I have misunderstood the Front Controller/Command and Controller Strategy pattern. Maybe the MVC gurus out there would have some thoughts on the matter.
    My issues:
    1.) Some CCS discussions seem to assign View presentation (sometimes called "dispatch", or "rendering", or "forwarding"?) to an ApplicationController. It seems puzzling to me, since only a concrete FrontController should include any knowledge of a concrete View structure. Shouldn't only a FrontController perform a logical-to-physical resource mapping, thus encapsulating knowledge whether a particular View is a separate, stand-alone Web page or a compound, argument-driven Swing object, and how to "present it" (by either redirecting to a Web page, or bringing a particular Swing object into the foreground)?
    2.) Some CCS discussions seem to introduce Client-specific implementation details at the ApplicationController level, for example "HTTP requests" or "HTTP responses". It seems puzzling to me, since I feel that every part of the framework, except for a concrete FrontController, should be completely independent of the nature of a Client making a request. Instead, I created a generic Request object w/arguments and have a concrete FrontController translate any client-specific details into such a generic Request, before delegating to an ApplicationController.
    3.) In the light of the (2.) above, I am not sure what constitutes a "response" from an ApplicationController back to a FrontController. It seems to me that the only universal "response" is a LogicalViewEnumeration: what View to present once a command has been completed, in many cases a "don't care", or a "show the requestor", or a "show a home page" (not every request has to result in changing a View). Well, perhaps a LogicalViewEnumeration as well as possible View arguments (?).
    4.) In the light of the (3.) above, I suspect that any failures in Request delegation, or Command execution, should be perhaps propagated back to a FrontController by exceptions only, since, say, a WebFrontController might want to show a click-through error page, when a SwingFrontController might prefer to show an error dialog box, a LogicalErrorViewEnumeration might not make sense at all in the context of a particular Client, for example a queueing Client.
    5.) In the light of the (4.) above, there is the question of an appropriate Request interface (into an ApplicationController), an appropriate Response interface (back into a FrontController), as well as an appropriate ViewArguments interface (into a FrontController and later into a View). The problem with generic Requests is that they can be created with nonsensical argument combinations, so shouldn't Requests be abstract and force proper arguments in concrete subclasses, through explicit constructors (in a sense, degenerate Commands)? The problem with Responses and ViewArguments is that... well, I have not found any formal discussion anywhere as to what those should look like. In most samples I have encountered, Responses include Client-specific implementation details, as mentioned in (2.), above.
    6.) Some CCS discussions seem to introduce a Flow Manager at the ApplicationController level. It seems puzzling to me, since the whole point of the Command and Controller Strategy flavor seems to be centralization of business logic execution within self-contained Command objects. Shouldn't Requests get associated with Handlers (objects capable of actually carrying out Requests) and transformed into Commands inside an ApplicationController, thus Commands themselves return appropriate LogicalViewEnumeration back to an ApplicationController, back to a FrontController? Let's consider a ShowMyShippingAddress request coming into the framework: unless such a Request is eventually treated as a Command returning a particular LogicalViewEnumeration, it is suddenly a Flow Manager "acting" as a business logic driver. I guess the question here is: except for a few special cases handled by a particular ApplicationController (authentication, error conditions, default behavior, etc.), should flow management be considered stand-alone, or always delegated to Commands?
    7.) Some CCS discussions seem to include an extra Request argument that specifies an ApplicationController to use (Request.Action="create", Request.Controller="account", Request.Username="me-me-me"), instead of using a Router inside of a FrontController to resolve to a particular ApplicationController through a generic action (Request.Action="createAccount", Request.Username="me-me-me"). I am not sure about the reason for such a design decision: why should a Client or a FrontController be allowed to concern itself with an implementation-level structure of the framework? Wouldn't any framework state -dependent ApplicationController resolution issues be best handled inside a Router, used by a FrontController to resolve [obtain] an appropriate ApplicationController, thus preventing Clients from ever forcing the framework into a possibly inconsistent behavior?
    Any comments appreciated...
    Thanks,
    Gary

    gniemcew wrote:
    1.) Some CCS discussions seem to assign View presentation (sometimes called "dispatch", or "rendering", or "forwarding"?) to an ApplicationController. It seems puzzling to me, since only a concrete FrontController should include any knowledge of a concrete View structure. Shouldn't only a FrontController perform a logical-to-physical resource mapping, thus encapsulating knowledge whether a particular View is a separate, stand-alone Web page or a compound, argument-driven Swing object, and how to "present it" (by either redirecting to a Web page, or bringing a particular Swing object into the foreground)?It is hard to tell without reading the actual discussion, but my guess is that the posters were either conflating or being loose with the distinction between a FrontController and an ApplicationController. The former is (normally) intimately tied to the actual view being used (HTTP, Swing, etc.) whereas the ApplicationController typically is not. Both are involved in dispatch and event processing. The former normally renders a view whereas the latter does not.
    gniemcew wrote:
    2.) Some CCS discussions seem to introduce Client-specific implementation details at the ApplicationController level, for example "HTTP requests" or "HTTP responses". It seems puzzling to me, since I feel that every part of the framework, except for a concrete FrontController, should be completely independent of the nature of a Client making a request. Instead, I created a generic Request object w/arguments and have a concrete FrontController translate any client-specific details into such a generic Request, before delegating to an ApplicationController.Generic is fine. However, you can become generic to the point where your Request and Response interfaces are only acting as "marker" interfaces (think of java.io.Serializable). Writing a truly generic controller is possible, but personally, I have never found the effort justified.
    gniemcew wrote:
    3.) In the light of the (2.) above, I am not sure what constitutes a "response" from an ApplicationController back to a FrontController. It seems to me that the only universal "response" is a LogicalViewEnumeration: what View to present once a command has been completed, in many cases a "don't care", or a "show the requestor", or a "show a home page" (not every request has to result in changing a View). Well, perhaps a LogicalViewEnumeration as well as possible View arguments (?).A given service (if you ascribe to SOA) should be the fundamental unit in your architectural design. A good application controller would be responsible for determining how to dispatch a given Command. Whether a Command pattern is used or whether service methods are invoked directly from your FrontController, the ApplicationController should enforce common service aspects. These include authentication, authorization, auditing, orchestration, validation, logging, error handling, just to name a few.
    The ApplicationController should ideally offload these aspects from a given service. The service would indicate how the aspects are to be applied (e.g., strong authentication required, x role required, fetching of existing process state, etc.) This allows services to be developed more quickly and to have these critical aforementioned aspects developed and tested centrally.
    Your FrontController, in contrast, is responsible for transforming whatever input it is designed to receive (HTTP form data posts, XML-RPC, etc.) and ensure that it honors the contract(s) that the ApplicationController establishes. There are no cut-and-dry decisions though about when a given piece of functionality should be ApplicationController or FrontController. Take error handling. Should I emit just a generic ServiceException or allow the FrontController to decide what to do with a more concrete checked exception? (The FrontController, in any case, should present the error to the user in a manner dictated by the protocol it serves).
    gniemcew wrote:
    4.) In the light of the (3.) above, I suspect that any failures in Request delegation, or Command execution, should be perhaps propagated back to a FrontController by exceptions only, since, say, a WebFrontController might want to show a click-through error page, when a SwingFrontController might prefer to show an error dialog box, a LogicalErrorViewEnumeration might not make sense at all in the context of a particular Client, for example a queueing Client.See above. Yes. However, the ApplicationController could easily 'hide' details about the failure. For example, any number of exceptions being mapped to a generic DataAccessException or even more abstractly to a ServiceFailureException. The ApplicationController could indicate whether the failure was recoverable and/or populate information necessary to speed up production support (e.g., mapping exceptions to error codes and/or providing a primary key in an error audit log table for support to reference). A given FrontController would present that information to the user in the method that makes sense (e.g., error dialog for Swing, error page for HTML, etc.)
    gniemcew wrote:
    5.) In the light of the (4.) above, there is the question of an appropriate Request interface (into an ApplicationController), an appropriate Response interface (back into a FrontController), as well as an appropriate ViewArguments interface (into a FrontController and later into a View). The problem with generic Requests is that they can be created with nonsensical argument combinations, so shouldn't Requests be abstract and force proper arguments in concrete subclasses, through explicit constructors (in a sense, degenerate Commands)? The problem with Responses and ViewArguments is that... well, I have not found any formal discussion anywhere as to what those should look like. In most samples I have encountered, Responses include Client-specific implementation details, as mentioned in (2.), above.See comment on marker interfaces above. Nothing, however, stops you from requiring a certain sub-type in a given service method. You can still pass in the interface and validate the proper type by an assert statement (after all, in the vast majority of situations, the proper service method should get the proper instance of a given Request object). IMO, the FrontController would create the Command instance which would be passed to the ApplicationController which would dispatch and invoke the proper service method. A model response would be received by the FrontController which would then render the appropriate view.
    gniemcew wrote:
    6.) Some CCS discussions seem to introduce a Flow Manager at the ApplicationController level. It seems puzzling to me, since the whole point of the Command and Controller Strategy flavor seems to be centralization of business logic execution within self-contained Command objects. Shouldn't Requests get associated with Handlers (objects capable of actually carrying out Requests) and transformed into Commands inside an ApplicationController, thus Commands themselves return appropriate LogicalViewEnumeration back to an ApplicationController, back to a FrontController? Let's consider a ShowMyShippingAddress request coming into the framework: unless such a Request is eventually treated as a Command returning a particular LogicalViewEnumeration, it is suddenly a Flow Manager "acting" as a business logic driver. I guess the question here is: except for a few special cases handled by a particular ApplicationController (authentication, error conditions, default behavior, etc.), should flow management be considered stand-alone, or always delegated to Commands?There are distinct kinds of flow management. For example, orchestration (or BPM) is properly at either the service or ApplicationController layers. However, determining which view to display is properly at the FrontController layer. The ApplicationController should receive a Command (with a populate Request) and return that Command (with a populated Response). Both the Request and Response are fundamentally model classes (within MVC). The FrontController is responsible for populating the Request and/or Command and rendering the Response and/or Command. Generic error handling is usually centralized for both controllers.
    gniemcew wrote:
    7.) Some CCS discussions seem to include an extra Request argument that specifies an ApplicationController to use (Request.Action="create", Request.Controller="account", Request.Username="me-me-me"), instead of using a Router inside of a FrontController to resolve to a particular ApplicationController through a generic action (Request.Action="createAccount", Request.Username="me-me-me"). I am not sure about the reason for such a design decision: why should a Client or a FrontController be allowed to concern itself with an implementation-level structure of the framework? Wouldn't any framework state -dependent ApplicationController resolution issues be best handled inside a Router, used by a FrontController to resolve [obtain] an appropriate ApplicationController, thus preventing Clients from ever forcing the framework into a possibly inconsistent behavior?I am not 100% sure of what you are getting at here. However, it seems to be the method by which commands are dispatched. They are in effect allowing a FrontController to dictate which of n ApplicationControllers should receive the request. If we allow a FrontController to directly invoke a service method, then the ApplicationController is simply a centralized framework that should always be invoked for each service method (enforced via AOP or some other mechanism). If there is a single, concrete ApplicationController which handles dispatch, then all FrontControllers communicate directly with that instance. It is really just a design decision (probably based on your comfort level with concepts like AOP that allow the ApplicationController to exist solely behind the scenes).
    I might have totally missed your questions, but those are my thoughts on a Monday. Best of luck.
    - Saish

  • 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

Maybe you are looking for

  • Problem in date compare

    Hi All, I have two oracle servers both are 9i. In one machine the date comparison is working file in another its not. I have come up with a sample pl/sql block which is DECLARE STARTDATE DATE; BEGIN STARTDATE := TO_DATE('08/09/2010','mm/dd/yyyy'); --

  • Reg customer expected price

    Hi guru's, In customer expected price we raise the sales order with EDI1&EDI2 condition types.we specify either price or value.we save the incomplete document.we raise the delivery and billing.billing will be blocked due to price error.autorization p

  • 3G in a 4G Land

    I am in an area that supposedly has 4G LTE service.  The best I get is 3G fluctuating with 1X.  I went to the local Verizon store recently in which they switched out the SIM card in the Jetpack.  They assured me I would now be getting 4G service.  My

  • Reinstalling iOS7 apps

    In an effort to clean up my apps I erased the iOS7 Compass and Passbook apps (surprised that this was possible as it hasn't been in previous iOS versions). Howeber, I would like to get them back without having to make a full restore. How do I do this

  • Running MBP with Snow Leopard 10.6.8. - Non Visible Dock Icons

    Several Apple Applications are no longer visible on the Dock. They haven't disappeared - they are there, but there is a blank space where they are. If I open one, there is a blue dot underneath it. Removing from Dock and returning it there and saying