PowerShell Script to empty recycle bin works locally but not remotely - powershell

I have the following PowerShell script to empty the recycle bin.
$recycleBin = (New-Object -ComObject Shell.Application).NameSpace(0xa)
$recycleBin.Items() | ForEach-Object -Process { Remove-Item -Path $_.Path -Force -Recurse }
The script works locally on my machine. I want to invoke the same script remotely, but it does not work. This script is meant to empty the recycle bin of the (primary) user that is signed in, and the machine has only C drive. I have been invoking remotely many other scripts like removing temporary files of browsers, getting system info, etc. They all work fine.
I am using System.Management.Automation library to invoke the script and I add the remote machine details and admin credentials needed to the Runspace. Here you can find details about the library.
Any ideas why this happens?

Related

Run powershell script within powershell script (Intune related)

This is Intune related but could probably apply outside the scope of Intune as well.
I wrote a PowerShell script that downloads a folder from an Azure blob storage and extracts the content. Within the extracted folder is another PowerShell script that I want to run.
The PowerShell script is deployed in Intune and runs successfully all the way up to the point where the second PowerShell script runs. From the log, it's running into a permission issue.
Scripts deployed through Intune are ran as administrator/system and don't require any local policy change to allow the execution of PowerShell scripts on the device. However on the device, the user account is only a standard user so they don't have permissions to execute PowerShell scripts. In the first script, I've included the "Set-ExclusionPolicy Bypass" command already.
I need to be able to deploy the script from Intune to the local device and essential run another script as the local user (non administrator account). I thought maybe I needed the local user to be included in the local administrators group to be able to run the second script but that did not work either.
Also read somewhere that PowerShell can run PowerShell scripts from other PowerShell scripts directly. The only time you need Start-Process for that is when you want to run the called script with elevated privileges (which isn't necessary here, since your parent script is already running elevated).
^^^Is this my issue? My script does include "Start-Process" to run the next powershell script.
Script below for reference.
New-Item -Path "C:\IT Drivers" -ItemType Directory ;
Invoke-WebRequest - Uri 'https://xyz.zip' -OutFile "C:\xyz.zip" ;
Expand-Archive -Path "C:\xyz.zip" -DestinationPath "C:\";
Set-ExclusionPolicy Bypass ;
Start-Sleep -Seconds 30 ;
Start-Process powershell "C:\xyz.ps1"
Any guidance would be appreciated, thank you!

Chef doesn't call the second line of the PS script

I'm using Chef Kitchen to do a POC. We have a PowerShell script which goes to a network path, sorts the build based on date [Install shield installer], copies to the VM in a folder.
This script works correctly when I run inside the VM manually using Power Shell. When I run using Chef Kitchen I don't get any error, the recipe is run but only the first line.I can see the folder called Build created in the VM.
I did an experiment and added a second line to create another folder, it worked correctly. So the issue is the logic I used to copy and paste the build doesn't seem to work with Chef.
The first line creates a new folder, the second and third sets the source and destination path. The fourth line copies the build from the network path [Sort by date to get the latest] to the VM. And the last one is to rename.
And also is there an efficient way to copy a file from a network path [Sorting by date] to a VM using Chef?
powershell_script 'CopyBuild' do
code <<-EOH
New-Item -ItemType directory -Path C:\Build
$source = gci \\BuildPath\Build | ? { $_.PSIsContainer } | sort CreationTime -Desc | select -f 1
$destination = "C:\Build"
Copy-Item "\\BuildPath\Build\$source\*" $destination
Get-ChildItem $destination -r -i "*app1*.exe" | Rename-Item -NewName {"Test.exe"}
EOH
end
I also tried this, calling the PS script:
cookbook_file 'getbuild.ps1' do
mode '0755'
end
This looks like a windows remoting problem, your powershell needs the right configuration to be allowed to access network shares.
To verify if this is the case: replace the UNC path and just copy a local directory - if this works you can dig further to setup the requirements for windows remoting, see the following links for further help:
Safely running windows automation operations that fail inside winrm or powershell remoting (see chapter No access to network resources)
Knife issue 655
enabling and using credssp
To sum these links up: you can schedule a local task in your PS which does the copy to achieve this, or setup credssp.

Why will PsExec not execute a .ps1 script remotely?

I am trying to write a script in PowerShell that gathers free space on the C: drive and then appends it to a .csv file on a network drive.
Our company does not have PowerShell enabled by default. Remote PowerShell commands are restricted. Because of this, I have to script things out, then kick them off using PsExec.
I have two scripts for this process. The first one, is the one I run from my machine, this script asks for my credentials and then uses a foreach loop to cycle through a .txt file with IP addresses telling each IP to launch the second script from a network drive. The second script gathers the free space, performs a math function on it, then appends the hostname and free space to a .csv file on the network.
However, the second script never runs. After the connection is established using PsExec, my console just sits there. It should kick off the script and then loop again to the next IP. I have tested the second script manually on some of the target machines with no issues.
Locally executed script:
$username = Read-Host "Username"
$outputPath = "\\network\directory\sub-directory\FileName.csv"
$IPpath = Read-Host "Enter the path for the list of IP addresses"
$IPs = Get-Content -Path $IPpath
Add-Content -Path $outputPath -Value """IP"",""Free Space"""
foreach ($IP in $IPs)
{
if (Test-Connection -Count 1 -ComputerName $IP -Quiet)
{
\\network\directory\subdirectory\psexec.exe -accepteula \\$IP -u domain\$username -h PowerShell -ExecutionPolicy Bypass -Command \\network\directory\sub-directory\diskSpaceCheck.ps1
}
else
{
Add-Content -Path $outputPath -Value """$IP"",""Offline"""
}
}
Remotely executed script (diskSpaceCheck.ps1):
$outputPath = "\\network\directory\sub-directory\FreeSpace.csv"
$hostname = hostname
$disk = Get-WmiObject Win32_LogicalDisk -Filter "DeviceID='C:'"
$freeSpace = [System.Math]::Round((($disk.FreeSpace) / 1GB))
Add-Content -Path $outputPath -Value "$($hostname), $($freeSpace)"
I don't think you can have an if statement inside a foreach also but I've tried it without the if test and got the same results. I can't figure out why the remote machine won't execute this script. I have another script that is copied to these machines and then executed in the same manner that works correctly.
Also, the target machines are locked down to limit their use for only specific purposes. These machines use a generic auto logon and generally have access to a few applications. Everything else is inaccessible, including Windows Explorer, Control Panel, etc. I tested this script on some of the machines local to my office, and it worked fine.
I was thinking maybe a networking latency issue? Can that impact PsExec or .ps1 scripts? I can remote onto the machine, log out, log in with my credentials and run the script while PsExec just sits at running the command I gave it.
Any advice would be appreciated.
This can occur if you are using PSExec to directly execute the Ps1 file. Instead use PSexec to execute PowerShell.exe and pass your ps1 file as a parameter.
Also check this question: Run PowerShell on remote PC
I figured it out. The script was running but it was just sitting there waiting for another command. I added a stop-process command to the script that runs remotely.
Stop-Process -Name powershell
Now it runs, and then exits with error code -1.

Powershell executing .exe file without the folder path

I am fairly new to powershell and I am trying to create a script that executes a .exe file. I can execute them on my machine no problem because the folder path is hard coded. The problem is that if I shift this script to another computer, the .exe it calls might be located in a different folder structure. Example
My computer:
D:\Folder1\subfolder\RunMe.exe
Client computer might be
D:\RunMe\subfolder\RunMe.exe
I just need it to execute the RunMe.exe no matter where it is. Is there a way to do this in powershell?
# 1. Get the location of RunMe.exe
$RunMe = Get-ChildItem -Path d:\* -Include RunMe.exe -Recurse;
# 2. Invoke RunMe.exe
Start-Process -FilePath $RunMe[0].FullName -Wait -NoNewWindow;

Powershell Get-ChildItem doesn't work properly on IIS directory

I was going to write up a simple alias 'iis' to invoke the IIS Manager, which is 'C:\Windows\System32\inetsrv\InetMgr.exe'
set-alias iis "OpenIIS.ps1"
and in the OpenIIS.ps1 I have
$item = "C:\Windows\system32\inetsrv\InetMgr.exe"
invoke-item -path $item
This doesn't work. The error I get is "The system cannot find the file specified"
In fact, just doing a Get-ChildItem on the inetsrv won't show the InetMgr.exe (no difference with -Force switch)
Get-ChildItem C:\Windows\system32\inetsrv\*.exe -force
Obviously I can see it in Explorer and I can launch it using cmd, but not with Powershell it seems. Also, Powershell is running as Administrator.
What is going on?
As a workaround I tried creating a link to the file and then invoking that link from Powershell. I now get a 'NotSpecified' Win32Exception.
I have originally used 64 bit Powershell, but get the same result on the x86 Powershell (both run as Administrator)
Are you at the elevated PowerShell prompt? Some system files may not show up unless you use -Force parameter with Get-ChildItem.
I think evidently the file InetMgr.exe is not there as when I do a get-childitem in the mentioned directory,it lists the "InetMgr.exe" there.
This may not be the problem with Get-ChildItem or the Alias you created but instead with ur IIS Server.