I'm using the following script to check if a new file was uploaded to a specific adress on my Mac. gotta switch to a windows PC
Any idea how to have the same function or similar on windows?
while ! wget
https://xxxxxxxxxxxx/xxxxxx/xx-$
sleep 10
done
afplay /System/Library/Sounds/Funk.aiff
say file found
osascript -e 'tell app "System Events" to display
dialog "Wow.. exciting file downloaded!"'
this is an example in powershell:
$var = $true
while($var){
try
{
$request = Invoke-WebRequest -Uri "https://de.wikipedia.org/favicon.ico" -OutFile "C:\fav.ico"
[System.Media.SystemSounds]::Asterisk.Play()
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[System.Windows.Forms.MessageBox]::Show("Wow.. exciting file downloaded!","Msg",0)
$var = $false
}
catch{
Start-Sleep -s 10
}
}
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-webrequest?view=powershell-7.2
How do you get Windows PowerShell to play a sound after .bat job has finished running?
Related
I have an update script for running the Dell Command Update tool. In short dcu-cli.exe. The thing now is than when i run the same script code on the computer local then everything runs OK but when i run the exact same code in a script with invoke-command(and yes i have full admin rights) than the exitcode is 2 meaning An unknown application error has occurred instead of 0 (everything OK)
It is a very large script so i created a new one to debug this. This is the shorted code:
Invoke-Command -ComputerName "MyComputer" -ScriptBlock {
$ExitCode = 0
#Declare path and arguments
$DcuCliPath = 'C:\Program Files (x86)\Dell\CommandUpdate\dcu-cli.exe'
$DellCommand = "/applyUpdates -autoSuspendBitLocker=enable -outputLog=C:\Dell_Update.log"
#Verify Dell Command | Update exists
If (Test-Path -Path $DcuCliPath) {
$objWMI = Get-WmiObject Win32_ComputerSystem
Write-Host ("Dell Model [{0}]" -f $objWMI.Model.Trim())
$serviceName = "DellClientManagementService"
Write-Host ("Service [{0}] is currently [{1}]" -f $serviceName, (Get-Service $serviceName).Status)
If ((Get-Service $serviceName).Status -eq 'Stopped') {
Start-Service $serviceName
Write-Host "Service [$serviceName] started"
}
#Update the system with the latest drivers
Write-Host "Starting Dell Command | Update tool with arguments [$DellCommand] dcu-cli found at [$DcuCliPath]"
$ExitCode = (Start-Process -FilePath ($DcuCliPath) -ArgumentList ($DellCommand) -PassThru -Wait).ExitCode
Write-Host ("Dell Command | Update tool finished with ExitCode: [$ExitCode] current Win32 ExitCode: [$LastExitCode] Check log for more information: C:\Dell_Update.log")
}
}
When i remove the Invoke-Command -ComputerName "MyComputer" -ScriptBlock { and then copy + run the script local on the PC then the exitcode = 0
What i also noticed than when i run the command via 'Invoke-Command' then there is also no log file created as i passed along in the arguments... So my best guess is something is going wrong with local an remote paths?
So what am i missing? I'm guessing it is something simple but i spend several hours to get this running without any luck...
Try running it this way. You should be able to see any output or error messages. I typically add to the path first rather than using & or start-process.
invoke-command mycomputer {
$env:path += ';C:\Program Files (x86)\Dell\CommandUpdate';
dcu-cli /applyUpdates -autoSuspendBitLocker=enable -outputLog=C:\Dell_Update.log }
Using start-process inside invoke-command seems pretty challenging. I can't even see the output of findstr unless I save it to a file. And if I didn't wait the output would be truncated. By default start-process runs in the background and in another window. There's a -nonewwindow option too but it doesn't help with invoke-command.
invoke-command localhost { # elevated
start-process 'findstr' '/i word c:\users\joe\file1' -wait -RedirectStandardOutput c:\users\joe\out }
#js2010, thanks for your additional help. Unfortunately this didn't helped either.
So i did some more debugging and it turns out it was a bug in the dcu-cli version running on my test machine, DOH...!!
On the test machine version 3.1.1 was running and on another machine version 4.0 was running and that worked fine via remote Powershell. So i looked for the release notes, which i found here: https://www.dell.com/support/kbdoc/000177325/dell-command-update
And as you can see in version 3.1.3 there was this fix:
A problem was solved where dcu-cli.exe was not executed in an external interactive session of PowerShell.
My university requires all computers to perform a web-based login in order to get-access to the internet, and claims that all users will log-off automatically in the mid-night (sounds strange, but it is true), so I am trying to write a powershell script (in Windows 10) to perform automatic login at mid-night.
My script is list here. It opens an IE process in the background (in a nonvisible way), fill in the username and password, login, and kills the IE process.
# If there are existing Internet Explorer processes, close it
$IE_Process = Get-Process iexplore -ErrorAction Ignore
if ($IE_Process) {
$IE_Close = Foreach-Object { $IE_Process.CloseMainWindow() }
}
Stop-Process -Name "iexplore" -ErrorAction Ignore
# Login Information
$url = "http://xxx.xxx.xxx.xxx/"
$username = "xxxxxxxx"
$password = "xxxxxxxx"
# Open an IE process
$ie = New-Object -com internetexplorer.application;
$ie.silent = $true
$ie.navigate($url);
while ($ie.Busy -eq $true)
{
Start-Sleep -s 1;
}
# The stupid webpage needs to submit twice
$ie.Document.getElementById("loginname").value = $username
$ie.Document.getElementByID("password").value = $password
$ie.Document.getElementById("button").Click()
Start-Sleep -s 1;
$ie.Document.getElementById("loginname").value = $username
$ie.Document.getElementByID("password").value = $password
$ie.Document.getElementById("button").Click()
# Close the IE process
$IE_Process = Get-Process iexplore -ErrorAction Ignore
if ($IE_Process) {
$IE_Close = Foreach-Object { $IE_Process.CloseMainWindow() }
}
Stop-Process -Name "iexplore" -ErrorAction Ignore
Remove-Variable -Name ie,username,password,url,IE_Process -ErrorAction Ignore
The script is saved as "login_IE.ps1". It may be poorly written as I am new to powershell, but it works. If I open an cmd window and execute the following command, I am logged in.
C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy RemoteSigned -File C:\Users\MyName\Documents\Powershell\login_IE.ps1
However, if I create a scheduled task in windows task scheduler executing this script, it doesn't work. I fill the "Program/script:" as:
C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe
and fill the "Add arguments (optional):" as:
-ExecutionPolicy RemoteSigned -File C:\Users\MyName\Documents\Powershell\login_IE.ps1
The scheduled task is run under my account (I am the only user of this computer).
If I run the scheduled task manually, in the task manager I can see two IE process opened in the "Background process", communicate with the internet, and then get killed, so I am pretty sure that the script has actually been executed. But I found I am not logged in since I don't have internet access, where could the problem be?
Any advice is really appreciated. Thanks in advance.
Similar type of issue I had, when trying to run the script directly from Powershell window it works as expected, but from the task scheduler or command line both not getting the desired results.
Commenting and adding lines like below in my script, help me to run the script from command line and task scheduler as well
$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
[Net.ServicePointManager]::SecurityProtocol =
[Net.SecurityProtocolType]::Tls12
Hope this helps anyone else.
for many days I am fighting with a script that I would like to run in order to control when a user plugges a USB stick in the workstation.
This is a simplified version of the script.
Unregister-Event RemovableDiskDetection
$query = "SELECT * FROM __InstanceOperationEvent WITHIN 5 WHERE TargetInstance ISA 'Win32_LogicalDisk' AND TargetInstance.DriveType=2"
Register-WmiEvent -Query $query -SourceIdentifier RemovableDiskDetection -Action {
$class = $eventArgs.NewEvent.__CLASS
$device = $eventArgs.NewEvent.TargetInstance.DeviceID
$wshell = New-Object -ComObject Wscript.Shell
switch($class)
{
__InstanceCreationEvent {
$path = $device + "\flag"
Write-Host "*** Checking the existence of the file $path"
if(Test-Path -Path $path)
{
$wshell.Popup("Inserted, device id: $device WITH flag",0,"Done",0x1)
}
else{
$wshell.Popup("Inserted, device id: $device WITHOUT flag",0,"Done",0x1)
}
}
__InstanceDeletionEvent {
$wshell.Popup("Removed, device id: $device ",0,"Done",0x1)
}
}
}
If I run the script from the Windows Powershell ISE it works as expected. If I open a CMD window and run the command "powershell -noexit -file basicUSBControl.ps1" , it also works as expected.
My issue is when I try to set the execution of this script for the whole computer affecting to any user who might log into the computer.
I tried via the Local Group Policy Editor. I went to the
Computer Configuration-->Windows Settings--> Scripts --> Startup
Then I chose Powershell script tab and set the same script as before. I also chose the option in the drop down box " Run Windows Powershell scripts first".
Then I proceed to restart the computer and log into it and nothing seems to happen whenever I plug any USB stick.
Any idea what might be happening?Could anyone help me out? I am getting crazy and, maybe it is just not possible to do what I need to do....
I also tried with a scheduled task, the resulted task status shows "Running" all the time but not event is caught, not popups showns when plug and unplug usb sticks... :/
Many thanks!
the solution was to create a GPO where the scheduled task is created.
there you can specify the user who will run the script, in my case,
%LogonDomain%\%LogonUser%
I need to log my powershell output. My ps file is something like this:
#Set-ExecutionPolicy Unrestricted
$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue"
$date = (Get-Date).tostring("MMddyy HHmmss")
$filename = 'C:\apierror\logs\' + $date + '.txt'
Start-Transcript -path $filename -append
$python = "C:\Python34\python.exe"
$python_path = "C:\script.py"
cd (split-path $python_path)
& $python $python_path
Stop-Transcript
Now, when I run this file directly from powershell, the output is logged correctly. But when I try to run it from taskscheduler - only some portion of the console output is stored in the file.
Any ideas why that might be?
Using transcript only stored partial output for some reason. I ended up using logs directly into the python file as opposed to powershell. Seems to be working correctly.
I have a functions that only works on some scensarios.
It works on Powershell ISE, but when I save the same thing in a .Ps1 file and run it, it doest not work.
I have the function as part of a big script. It works and open the Window when I run it on Windows 7 but doest not run on Windows Server 2008 R2.
Why?
The script with the function and its calling is:
Function Get-SaveFileTxt($initialDirectory)
{
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |
Out-Null
$SaveFileDialog = New-Object System.Windows.Forms.SaveFileDialog
$SaveFileDialog.initialDirectory = $initialDirectory
$SaveFileDialog.AddExtension = $true
$SaveFileDialog.DefaultExt = "txt"
$SaveFileDialog.filter = "Text Files (*.txt)| *.txt"
$SaveFileDialog.ShowDialog() | Out-Null
$SaveFileDialog.filename
}
Get-SaveFileTxt
Not sure if this is the case here but I remember a bug that the opened dialog doesn't take focus and appear behind other opened windows. Can you confirm?
UPDATE:
Set the ShowHelp property to $true.
$SaveFileDialog.ShowHelp = $true
It works in the ISE because ISE's apartment state is STA by default and your powershell mode is MTA, you can check it with:
[System.Threading.Thread]::CurrentThread.ApartmentState
Your code will work if you open powershell in STA mode:
powershell.exe -STA