How to pass local variable to Invoke-Command's -ScriptBlock

后端 未结 2 1512
庸人自扰
庸人自扰 2020-12-20 06:26

I am trying to execute following PowerShell script from Server-2 against Server-1 (i.e. Remote server):

$DBServer = \'Server1\' 

Invoke-Command -ComputerNam         


        
2条回答
  •  春和景丽
    2020-12-20 07:16

    I will not implement your code but will explain through a simple example so that you can implement it accordingly.

    Suppose you need to start a website hosted on IIS. I have declared the variables. In the function u can assign values to variables as, it should have been like this, instead of $args[0], it should have been $abc, but I have I assigned the value of variable runtime. u can also assign multiple values by separating it with a comma, like

    -ScriptBlock {Start-Website $args[0] $args[1]} -ArgumentList $xyz, $abc

    Code Snippet
    
       $User="UserName"
       $Password="password"
       $abc="MyWebsite"
       $xyz="MyWebsite2"
       $ComputerName = "MyComputerName"
       $pword = ConvertTo-SecureString -String $Password -AsPlainText -Force
       $credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $User, $pword
    
       function StartIIS($abc)
       { 
         Invoke-Command -ComputerName $ComputerName -Credential $credential -ScriptBlock {Start-Website $args[0]} ArgumentList $abc
       }  
    
       StartIIS($abc)
    

提交回复
热议问题