开发者

powershell v2.0 passing variable computername parameter from a batch cmd file

开发者 https://www.devze.com 2023-03-03 20:18 出处:网络
Good Day All I want to set up a common script where I can pass the server name from a .bat script when calling the .ps1

Good Day All

I want to set up a common script where I can pass the server name from a .bat script when calling the .ps1

In my bat script I have this statement:

set setver_name=our2008server
powershell -ExecutionPolicy RemoteSigned 
    -NonInteractive 
    -NoProfile 
    -command 
        "& '\\serverd1\d$\Program Files\%run_dir%\Dcls\PS\Stop_Bkgnd_%run_env%_01.ps1' " 
    -server_name %server_name%

in my ps1 script I have:

gwmi win32_service -Computername $server_name -filter "name = 'BackgroundQueue'"  | 
    % {$_.StopService()}

If I replace the $server_n开发者_高级运维ame with the actual server name it works fine. Just cannot get the variable from the .bat file to be recognized in the .ps1.

Any help would be greatly appreciated.

BobZ


Update your script to use param:

param($server_name)
gwmi win32_service -Computername $server_name -filter "name = 'BackgroundQueue'"  | 
% {$_.StopService()}

And while calling, move the -server_name %server_name% to within the command.

set setver_name=our2008server
powershell -ExecutionPolicy RemoteSigned 
    -NonInteractive 
    -NoProfile 
    -command 
        "& '\\serverd1\d$\Program Files\%run_dir%\Dcls\PS\Stop_Bkgnd_%run_env%_01.ps1 -server_name %server_name%' "


The easiest way is to use the $args variable. This is an array containing all the arguments passed to the PowerShell script.

Sample usage:

Write-Host "Num Args:" $args.Length;
foreach ($arg in $args)
{
  Write-Host "Arg: $arg";
}

$args[0]
$args[1]

So, in your example, I would change the command parameter to read

// Note the change at the end of this string
-command "& '\\path\to\my\powershell_script.ps1' %setver_name%"

and change the PS1 file to be

// Note I have used $args[0].
gwmi win32_service -Computername $args[0] -filter "name = 'BackgroundQueue'"  | 
    % {$_.StopService()}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号