PowerShell ISE vs Script - windows

I am playing around powershell the idea is simple:
I want to verify if certain TCP port is open.
Now, I can run this as PowerShell script or I can run it in ISE.
Now, in ISE everything is fine, the script runs as supposed to.
When I run it as PowerShell Script however, I am getting error message:
Method invocation failed because [System.Net.Sockets.TcpClient] does not contain a method named 'ReceiveTimeout'.
At P:\checkTCP80.ps1:7 char:1
+ $tcpClient.ReceiveTimeout(5)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Code:
$servery = gc .\servers.txt
foreach ($server in $servery)
{
$tcpClient = New-Object System.Net.Sockets.TCPClient
$tcpClient.ReceiveTimeout(5)
$tcpClient.Connect($server,80)
Write-Host ($server, $tcpClient.Connected)
}
I have 2 questions:
How come, that the output parameter works just fine from ISE but does not work when this is launched as a script?
How to fix it?

According to the MS documentation on this class ReceiveTimeout is a property and not a method.
Try changing $tcpClient.ReceiveTimeout(5) to $tcpClient.ReceiveTimeout = 5

Related

The Win32 internal error "A device attached to the system is not functioning" 0x1F occurred while setting 2 the console window title

I have a PowerShell script that get a response from an API:
$test = Invoke-RestMethod -Uri $url -Method Get -ContentType application/json -UseDefaultCredentials
Then, iterate the response with foreach:
$test.value | foreach {
# Do something
}
In my PC it works great, but I want it will run automatically so I created a TFS build definition and it runs in our build servers.
During the build I get the following error in the middle of the foreach:
foreach : The Win32 internal error "A device attached to the system is not functioning" 0x1F occurred while setting
the console window title. Contact Microsoft Customer Support Services.
At D:\AGT\Test\01\_temp\test.ps1:9 char:17
+ $builds.value | foreach {
+ ~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (:) [ForEach-Object], HostException
+ FullyQualifiedErrorId : SetConsoleWindowTitle,Microsoft.PowerShell.Commands.ForEachObjectCommand
If I have log-in to the server and run the script, it works. only during the TFS build it doesn't work.
I googled it a lot but couldn't solve it. any idea?

GetScheduled-Job doesn't return any job

I'm trying to use PowerShell to add a trigger to an existing scheduled task.
I'm using Windows 10 & PowerShell 5
When I run:
Get-Scheduled-Job -Name TASK_NAME
I receive the error:
>Get-ScheduledJob : A scheduled job definition with Name sanityInstaller could not be found.
At line:1 char:1
+ Get-ScheduledJob sanityInstaller
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [Get-ScheduledJob], RuntimeException
+ FullyQualifiedErrorId : ScheduledJobDefinitionNotFoundByName,Microsoft.PowerShell.ScheduledJob.GetScheduledJobCommand
It seems that even when I run the same command with no parameter it's expected to return all jobs but it returns an empty result.
In the Task Scheduler there's no such folder as /Microsoft/Windows/PowerShell/ScheduledJobs and even after I created it and a new task inside it doesn't return it.
What am I missing here ?
Get-ScheduledJob gets only scheduled jobs that are created by the
current user using the Register-ScheduledJob cmdlet.
Source.
You are looking for the Get-ScheduledTask cmdlet.

Powershell: Variable assignment triggers module import

This code works from the Powershell command line but generates an error when run from a script:
$key = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced'
Set-ItemProperty $key Hidden 1
When I run it from my script, I get the following error:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer : The module 'HKEY_CURRENT_USER' could not be
loaded. For more information, run 'Import-Module HKEY_CURRENT_USER'.
At C:\Users\mybitch\Desktop\VSS-Customize-Desktop.ps1:19 char:6
+ $key=HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (HKEY_CURRENT_US...ersion\Explorer:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CouldNotAutoLoadModule
This is a simple assignment...Why would Powershell try to import HKEY_CURRENT_USER as a module? Why is the behavior so different from the Powershell command line?
The error message betrays the problem. In your script, apparently you are doing this:
$key = HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer
That is an invalid assignment. You should be doing as you describe:
$key = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced'
Make sure in the script you have the User Hive being loaded, for example if you are running it from a task scheduler you will need it to load a hive for it to have the effect that you want.

Copy files from corrupted HD using a powershell script

I am trying to use a script that ignores I/O errors on a HD, to copy whatever is good there into another HD.
I found this script here : http://81.165.15.172:1983/blog/2013/06/02/ignoring-device-io-errors-during-copy-with-powershell/comment-page-1/
(https://raw.github.com/DavorJ/PS-ForceCopy/master/Force-Copy.ps1)
that does just that...but i cant get it to work.
I am trying with command :
.\Force-Copy.ps1 -SourceFilePath "I:\Downloads\" -DestinationFilePath "H:\Downloads" -MaxRetries 6
but it gives me this weird error:
F:\SSDU\Desktop\Force-Copy.ps1 : Cannot validate argument on parameter 'SourceFilePath'. The "Test-Path -LiteralPath $_ -Type Leaf" validation script for the argument with value "I:\Downloads\" did not return true. Determine why the validation script failed and then try the command again.
At line:1 char:34
+ .\Force-Copy.ps1 -SourceFilePath "I:\Downloads\" -DestinationFilePath
"H:\Downlo ...
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Force-Copy.ps1], ParameterBind
ingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Force-Copy.ps1
Anyone knows how to use this in win-8 64-bit ?
-Thanks
So, it's not a PowerShell solution, but for getting whatever you can off a dying drive I recommend using Roadkil's Unstoppable Copier. You can download it from the author at:
http://www.roadkil.net/program.php/P29/Unstoppable%20Copier
I have had good success with that one.

Is there a guide to the (somewhat) convoluted PowerShell syntax? Example with Biztalk

I should probably not ask a generic question with a specific example, but I have a hard time translating some basic commands from the PowerShell console to reusable functions and custom cmdlets. Is there a definitive guide to the syntax of PowerShell somewhere, with gotchas, hints and tips?
For instance, I'm trying to create a function in order to automate the administration of BizTalk Host instances. The following function does not work (fails at runtime) whereas each individual line works and performs as expected when individually pasted in a PowerShell console.
function AddNewHostInstance([string]$ServerName, [string]$HostName, [string]$Login, [string]$Password)
{
[System.Management.ManagementObject]$objServerHost = `
([WmiClass]"root/MicrosoftBizTalkServer:MSBTS_ServerHost").CreateInstance()
$objServerHost["ServerName"] = $ServerName
$objServerHost["HostName"] = $HostName
$objServerHost.Map()
$name = "Microsoft BizTalk Server " + $HostName + " " + $ServerName
[System.Management.ManagementObject]$objServerHost = `
([WmiClass]"root/MicrosoftBizTalkServer:MSBTS_HostInstance").CreateInstance()
$objHostInstance["Name"] = $name
$objHostInstance.Install($Login, $Password, $True)
}
By the way, the error I receive in this particular case is this one:
PS C:\Users\username> createHostInstances $server, $host, $user, $pwd
Exception calling "Map" : "Invalid parameter "
At line:14 char:39
+ $objServerHost.Map <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WMIMethodException
Exception calling "Install" : "Instance of the WMI class is not found.
No instance was found with the specified key. This could be the result of the instance being deleted by another BizTalk Admin session."
At line:19 char:29
+ $objHostInstance.Install <<<< ($Login, $Password, $True)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WMIMethodException
PS C:\Users\username>
[Edit] After further investigation, it seems that the function does not like assigning properties to WMI object via a variable. If I hardcode all values (instead of relying on the supplied function parameters), then it works as expected !
Basically, this works:
# Using hard-coded value
$objServerHost["HostName"] = "TestHost"
Whereas this, does not:
# Using function supplied parameter
$objServerHost["HostName"] = $HostName
Still, I don't understand why...
As far as guides go, the best book out there is Windows PowerShell in Action by Bruce Payette. There is a second edition due in February but you can get early access to the electronic draft. There are also a couple of free books out there. Mastering PowerShell by Dr. Tobias Weltner and I also have a short < 60 pages eBook - Effective Windows PowerShell. This last one covers a number of gotchas as well as providing you with a mental model for how PowerShell works.
WRT the error, I wonder if you would have better luck using PowerShell's built-in support for WMI e.g.:
$namespace = 'root/MicrosoftBizTalkServer'
$host = Get-WmiObject -namespace $namespace -class MSBTS_HostInstance
See if the resulting WMI object has the appropriate data & methods (Map & Install):
$host | fl *
$host | Get-Member
Regarding the Map() error, sometimes with WMI you need to drop back and instead do $objServerHost.psbase.Invoke("Map"). Other than that, I've got a few sample PowerShell scripts for BizTalk administration you might find useful as guides.

Resources