批处理判断文本文件首行是否以指定字符串开头。


PowerShell交流中心分类: Powershell基础批处理判断文本文件首行是否以指定字符串开头。
0
mad_frog asked 9年 ago

有两个文件,iplist和config
内容分别为【iplist】
192.168.1.1
192.168.1.2
内容分别为【config】
comd:::get-culture
comd:::echo hello
file:::C:\Users\Administrator\Desktop\test C:\Users\Administrator\Desktop
想要实现批处理,如果config文件行首位comd,则在iplist 远程服务器上执行后面的命令 如果config文件行首位file,则需要把本地的文件拷贝到远程
刚学,我大概是这么写的
[array]$ipaddress = Get-Content .\iplist
[array]$command = Get-Content .\config
foreach($ip in $ipaddress)
{foreach($comd in $command){
$pwd= ConvertTo-SecureString “test” -AsPlainText -Force
$cred= New-Object System.Management.Automation.PSCredential(“administrator”,$pwd)
if (开头为conmd{运行命令}
elseif(开头为file) {传送文件}}}  
判断部分不会写,请麻烦帮小弟补充一下

mad_frog replied 9年 ago

还有,如果config文件中的一行已“#”开头,则表示注释,不运行,跳过,如:#comd:::get-culture

2 Answers
0
Mooser Lee 管理员 answered 9年 ago

判断文本文件首行是不是由特定子串开始的,可以这样判断:

(Get-Content .\a.txt | select -First 1 ).startswith('comd')

或者:

(Get-Content .\a.txt | select -First 1 ) -match '^comd'
mad_frog replied 9年 ago

恩,可以了,我想在远程服务器上运行一个命令,如:if ( 2 -ne 1 ){invoke-command -computername $ip -Credential $cred -ScriptBlock{“$command”}} ScriptBlock 的内容是一个变量,好像执行不了,不知道如何引用它

0
Mooser Lee 管理员 answered 9年 ago
$psSession= New-PSSession -ComputerName $server
  
  # invoke command.
 Invoke-Command -Session $psSession -ScriptBlock {
  param($client)
  'server={0},client={1},time={2}' -f $env:COMPUTERNAME,$client,(get-date)
 } -ArgumentList $env:COMPUTERNAME
Mooser Lee 管理员 replied 9年 ago

参数要在ScriptBlock指定,同时在-ArgumentList中传递。

mad_frog replied 9年 ago

谢谢,