我有一个插入查询,它没有正确插入,真的很烦人。我将简要地解释我所尝试的以及我实际想要实现的目标。
我的PS脚本的作用:
- 从数据库表中ping每台计算机
- 如果ping成功,让username从计算机登录
- 在数据库表中插入以下值:用户名、主机名、联机(true/false)
下面是不断出现的问题。
问题1:如果我使用以下命令:
$username=获取WMIObject-ComputerName$工作站-类别Win32_ComputerSystem |选择对象-扩展属性用户名;
它将插入如下用户名值:SUPER/user1这是可以的,但我想去掉"SUPER/",在插入之前只保留实际用户名"user1"。
我试着使用下面的一个,但它不起作用:
$username = Get-WMIObject -ComputerName $workstation -Class Win32_ComputerSystem | Select-Object -ExpandProperty -replace '^.*\' Username;
问题1中的命令将给我以下两个错误:
无法处理参数,因为参数"obj"的值为null。更改参数"obj"的值设置为非null值
和
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
关于问题1,请尝试以下操作:
$username = (Get-WMIObject -ComputerName $workstation -Class Win32_ComputerSystem).UserName
$username = $username.split("")
$username = $username[1]
问题2是由于远程机器上的问题。有关一些调试帮助,请参阅微软的文档:Technet。
尽管本文是针对MSServer量身定制的,但大部分内容也应该适用于客户端机器。