【发布时间】:2014-10-22 17:07:37
【问题描述】:
我的这个插入查询没有正确插入,真的很烦人。我将简要说明我尝试了什么以及我真正想要实现的目标。
我的 PS 脚本的作用:
- 从数据库表中对每台计算机进行 ping 操作
- 如果 ping 成功,则从计算机获取登录用户名
- 将以下值插入数据库表:用户名、主机名、在线(真/假)
下面是不断出现的问题。
问题一:如果我使用如下命令:
$username = Get-WMIObject -ComputerName $workstation -Class Win32_ComputerSystem | Select-Object -ExpandProperty 用户名;
它会像这样插入用户名值:SUPER/user1,这没关系,但我想去掉“SUPER/”,在插入之前只保留实际的用户名“user1”。
我尝试使用下面的一个,但它不起作用:
$username = Get-WMIObject -ComputerName $workstation -Class Win32_ComputerSystem | Select-Object -ExpandProperty -replace '^.*\\' Username;
问题 1 中的命令会给我这两个错误:
无法处理参数,因为参数“obj”的值为空。更改 将参数“obj”的值设置为非空值。
和
Get-WmiObject : RPC 服务器不可用。
如何忽略这两个错误?
我希望有人可以帮助我,因为它真的很烦人。先谢谢大家了。
Powershell 脚本:
foreach($pcname in $workstation_list){
$command = $connection.CreateCommand();
$command.Connection = $connection;
$command.CommandText = "INSERT INTO workstation_userlogged
(username,hostname,online)
VALUES (@username,@hostname,@status)";
### =============================================================
### values to be assigned as a parameters
### =============================================================
$workstation = $pcname;
$test_ping = Test-Connection -ComputerName $workstation -Count 1 -ErrorAction SilentlyContinue;
$status = [bool](Test-Connection $workstation -Quiet -Count 1 -ErrorAction SilentlyContinue);
#if status is TRUE get username
if($test_ping)
{
$username = Get-WMIObject -ComputerName $workstation -Class Win32_ComputerSystem | Select-Object -ExpandProperty Username;
echo $username;
#echo -replace '^.*\\' $username;
#if ping succeeds but no user is logged
if($username -eq "")
{
$username = "no user logged";
}
} #end if
#if ping DOES NOT succeed set username value to NULL and status to FALSE
elseif(!$test_ping)
{
$username = [DBNull]::Value;
}
### =============================================================
### Assign parameters with appropriate values
### =============================================================
$command.Parameters.Add("@username", $username) | Out-Null
$command.Parameters.Add("@hostname", $workstation) | Out-Null
$command.Parameters.Add("@status", $status) | Out-null
### =============================================================
### Execute command query
### =============================================================
try{
$command.ExecuteNonQuery() | out-null;
Write-Host "Successfully inserted in Database";
}
catch{
Write-Host "Caught the exception";
Write-Host "$_";
}
### =============================================================
### clear parameter values
### =============================================================
$command.Dispose()
$workstation = "";
$username = "";
$status = "";
$test_ping = "";
}#end for each loop
【问题讨论】:
标签: mysql powershell powershell-2.0 powershell-ise