powershell remote

非 Y 不嫁゛ 提交于 2021-02-10 18:10:18

问题


I am trying to run this from my local machine (Win7 & PS v2.0)

cls
$sess = Enter-PSSession -ComputerName blmcrmpoc
Invoke-Command -Session $sess -Scriptblock
{
$path = "C:\inetpub\logs\LogFiles"
$lastWrite = (Get-Date).AddDays(-90)
$oldLogs = Get-ChildItem -path $path -Recurse -Filter *.log | Where {$_.LastWriteTime -le $lastWrite}
if ($oldlogs.count -gt 0)
{foreach ($log in $oldLogs)
{$log.Delete()}}}

But I get this error.

***Invoke-Command : Cannot validate argument on parameter 'Session'. The argument is null or empty. Supply an argument that is not null or empty and then try the command again.

What am I missing?


回答1:


Try:

cls
$sess = New-PSSession -ComputerName blmcrmpoc
Invoke-Command -Session $sess -Scriptblock
{
    $path = "C:\inetpub\logs\LogFiles"
    $lastWrite = (Get-Date).AddDays(-90)
    $oldLogs = Get-ChildItem -path $path -Recurse -Filter *.log | Where {$_.LastWriteTime -le $lastWrite}
    if ($oldlogs.count -gt 0)
    {
        foreach ($log in $oldLogs)
        {
            $log.Delete()
        }
    }
}

With Enter-PSSession you ENTER a pssession(you start remoting it so you could write the commands directly as if it were the local machine). If you want to use Invoke-Command on a specific session, you create the session using New-Session because this creates a session without entering it.




回答2:


How to access argument list for scriptblock

ArgumentList is based on use with scriptblock commands, like:

you have to pass arugments for script block..


    cls
    $sess = Enter-PSSession -ComputerName blmcrmpoc
    Invoke-Command -Session $sess -Scriptblock
    {
    $path = "C:\inetpub\logs\LogFiles"
    $lastWrite = (Get-Date).AddDays(-90)
    $oldLogs = Get-ChildItem -path $path -Recurse -Filter *.log | Where {$_.LastWriteTime -le $lastWrite}
    if ($oldlogs.count -gt 0)
        {
       $xArgvalue= arg[0]
    $yArgvalue= arg[1]
    foreach ($log in $oldLogs)
     {
     $log.Delete()
     }
        }
    } -ArgumentList $x,$y

I found on below link how to pass arguments to script block



来源:https://stackoverflow.com/questions/14468278/powershell-remote

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!