0

我试图弄清楚如何编写 powershell 脚本,如果 powershell 无法连接到 \10.10.10.10\C$\Users,它应该尝试连接到 \10.10.10.10\C$\Documents and Settings

到目前为止,我有以下代码

$Win32OS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName '10.10.10.10'
$SysDrv = $Win32OS.SystemDrive
$SysDrv = $SysDrv.Replace(":","$")
$ProfDrv = "\\" + '10.10.10.10' + "\" + $SysDrv
$ProfLoc = Join-Path -Path $ProfDrv -ChildPath "User"

try
{
    Get-ChildItem $ProfLoc | ? { $_.PsIsContainer} | Sort LastWriteTime -Descending | Select -expand  Name -First 1
}
catch [Exception]
{
     return "CannotFindLastUser"
}

如果路径 \10.10.10.10\C$\Users 不存在,则会出现错误

Get-ChildItem : Cannot find path '\\10.10.10.10\C$\Users' because it does not exist.

如何更改代码以使其尝试连接到 \10.10.10.10\C$\Documents and Settings,否则会引发用户友好消息

编辑

这是整个脚本,其中参数的格式为“sender-ip=10.10.10.10”

$line_array = @()
$multi_array = @()
[hashtable]$my_hash = @{}
$Sender_IP = $NULL
$Win32OS = $NULL
$Build = $NULL
$folder = $NULL
$SysDrv = $NULL

foreach ($i in $args){
   $line_array+= $i.split(" ")
}

foreach ($j in $line_array){
    $multi_array += ,@($j.split("="))
}

foreach ($k in $multi_array){
    $my_hash.add($k[0],$k[1])
}


$Sender_IP = $my_hash.Get_Item("sender-ip")

try{
    Test-Connection $Sender_IP -count 1 -ErrorAction Stop | out-null
}
catch [Exception]
{
    $userId = "userId=CannotPing"
    return $userId 
}

try{
    $OS = (Get-WmiObject Win32_OperatingSystem -ComputerName $Sender_IP).Name
}
catch [Exception]{
    $userId = "userId=CannotConnectToWMI"
    return $userId
}


$Win32OS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $Sender_IP
$SysDrv = $Win32OS.SystemDrive
$SysDrv = $SysDrv.Replace(":","$")
$ProfDrv = "\\" + $Sender_IP + "\" + $SysDrv
$ProfLoc = Join-Path -Path $ProfDrv -ChildPath "Users"

try{
    $userId = Get-ChildItem $ProfLoc | ? { $_.PsIsContainer} | Sort LastWriteTime -Descending | Select -expand  Name -First 1
    $userId = "userId="+$userId
    return $userId
}catch [Exception]
{
    $userId = "userId=CannotFindLastUser"
    return $userId
}
4

1 回答 1

1

使用Test-Pathcmdlet 确定路径是否存在和/或是否可用。

您可能希望Test-Connection在测试路径之前使用 ping 服务器。

于 2013-10-22T13:08:23.233 回答