我有这个插入查询没有正确插入,真的很烦人。我将简要解释一下我的尝试以及我实际想要实现的目标。
我的PS脚本的作用:
现在这里出现的问题一直存在。
问题1:如果我使用以下命令:
$ 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
答案 0 :(得分:0)
关于问题1,试试这个:
$username = (Get-WMIObject -ComputerName $workstation -Class Win32_ComputerSystem).UserName
$username = $username.split("\")
$username = $username[1]
问题2是由于远程计算机上的问题。有关一些调试程序帮助,请查看Microsofts文档:Technet。
尽管本文是针对MS Server量身定制的,但大多数文章也适用于客户端计算机。