这段代码我的老师把它作为家庭作业给了我们,它不能和我一起工作

时间:2017-01-29 20:05:21

标签: powershell

基于以下.ps1程序。编写一个程序来检查用户" shu"如果不存在则会创建它。

Write-Host "checking users"$testUser="hgallo"
$checkUser = Get-WmiObject -Class Win32_UserAccount -Filter  "LocalAccount='True'"  | Select-String -Pattern $testUser

if($checkUser -ne $null) {
  Write-Host "user $testUser found"
} else {
  Write-Host "user $testUser not found"    
}

这是我的功课,我不擅长编码 你能帮帮我吗。

以下是错误Select-String

Cannot bind argument to parameter 'Pattern' because it is null. 
At line:1 char:107 
+ $checkUser=Get-WmiObject -Class Win32_UserAccount -Filter  "LocalAccount='True'"  | select-string -pattern <<<<  $tes tUser     
    + CategoryInfo          : InvalidData: (:) [Select-St

1 个答案:

答案 0 :(得分:2)

VonPryz是对的,

请尝试以下代码

Write-Host "checking users"
$testUser="hgallo"

$checkUser = Get-WmiObject -Class Win32_UserAccount -Filter  "LocalAccount='True'"  | Select-String -Pattern $testUser

if($checkUser -ne $null) {
  Write-Host "user $testUser found"
} else {
  Write-Host "user $testUser not found"    
}

代码中的错误表明-Pattern参数失败,因为变量$testuser为空。这是因为第一行代码的格式化。

格式错误的代码:

Write-Host "checking users"$testUser="hgallo"

正确格式化代码:

Write-Host "checking users"
$testUser="hgallo"