[英]how to delete a folder using invoke command in powershell
First time asking a question here after using it for a long time.用了很久第一次在这里提问。
I'm currently making a powershell script to delete userdata when they left the company for a month.我目前正在制作 powershell 脚本,以在他们离开公司一个月后删除用户数据。
I already tried deleting the folder using the normal remove-item and this works however this is a very slow process when going over the network.我已经尝试使用普通的 remove-item 删除文件夹,这可行,但是通过网络时这是一个非常缓慢的过程。
I then found out about the invoke-command function which can run on a remote computer.然后我发现了可以在远程计算机上运行的调用命令 function。 Now i can't seem to get this working.
现在我似乎无法让它工作。
I keep getting the error that the path is not found.我不断收到找不到路径的错误。 However it seems like powershell is changing my path.
然而,似乎 powershell 正在改变我的道路。 How can i prevent this from happening?
我怎样才能防止这种情况发生?
Cannot find path 'C:\Users\admcia\Documents\P$\PERSONAL\JOBA' because it does not exist.
+ CategoryInfo : ObjectNotFound: (C:\Users\admcia...$\PERSONAL\JOBA:String) [Remove-Item], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand
+ PSComputerName : ODNDATA
my code is the following: Note that P$ is the local drive letter on the server.我的代码如下: 请注意,P$ 是服务器上的本地驱动器号。 Also note That $item.SamAccountName is used for creating foldername.
另请注意 $item.SamAccountName 用于创建文件夹名称。 (we use Samaccountname as the name of the users folder.
(我们使用 Samaccountname 作为用户文件夹的名称。
$localPath1 = "P$" + "\PERSONAL\" + $item.SamAccountName
$serverName = "Remotecompter"
Invoke-Command -ComputerName $serverName -ScriptBlock { Remove-Item $using:localPath1 -Force -Recurse -Confirm:$false }
If as seen from your local machine, the drive is \\Remotecomputer\P$\
, then for the remote computer (where the code is executed) the path is just P:\
.如果从您的本地计算机上看到,驱动器是
\\Remotecomputer\P$\
,那么对于远程计算机(执行代码的地方),路径就是P:\
。
To combine strings into a path, I would suggest you better use the Join-Path cmdlet rather than concatenating the strings with '+'要将字符串组合成路径,我建议您最好使用 Join-Path cmdlet,而不是使用“+”连接字符串
Try尝试
$localPath1 = Join-Path -Path 'P:\PERSONAL' -ChildPath $item.SamAccountName
$serverName = "Remotecompter"
Invoke-Command -ComputerName $serverName -ScriptBlock { Remove-Item $using:localPath1 -Force -Recurse -Confirm:$false }
You can use -ArgumentList in Invoke command,您可以在 Invoke 命令中使用 -ArgumentList,
Invoke-Command -ComputerName $serverName -ScriptBlock {
param($localPath1)
Remove-Item $localPath1 -Force -Recurse -Confirm:$false
} -ArgumentList($localPath1)
make sure your path is correct, and if it does not work try to hardcode the path in your code.确保您的路径正确,如果它不起作用,请尝试在代码中对路径进行硬编码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.