Invoke-Command Powershell "Window Title Cannot be longer than X chacracters" - powershell

I am trying to run a script remotely using Powershell, the script still runs, but I receive an error Invoke Command : Window Title cannot be longer than 1023 characters.
Here is my code:
Invoke-Command -ComputerName Test -FilePath "\\Some\File\Path.ps1"
I realize what is occuring when running the line in ISE, it places the comments in the header of the script into the files name. Is there a way to prevent this action? I can use the option ErrorAction SilentlyContinue which suppresses the error, but it also suppresses all other errors which is not ideal.

How about setting the Window Title explicitly? That should avoid the window title being anything except what you specifically want.
$host.UI.RawUI.WindowTitle = 'Windows PowerShell';

This web link albeit VBS, does provide clarity and a walk-through for your situation.
https://blogs.technet.microsoft.com/heyscriptingguy/2005/06/02/how-can-i-display-more-than-1023-characters-in-a-custom-message-box/
This is a more common situation/issue than you would think.
HTH,
Kent

I know adding another answer may not always be agreeable, but had another thought about this..
Instead of displaying a Message Box to the user, you could craft an HTML file and display to the user..
get-service | ConvertTo-Html -Title "Services" -Body "<H2>The result of get-service</H2> " -Property Name,Status |
foreach {if($_ -like "*<td>Running</td>*"){$_ -replace "<tr>", "<tr bgcolor=green>"}elseif($_ -like "*<td>Stopped</td>*"){$_ -replace "<tr>", "<tr bgcolor=red>"}else{$_}} > c:\services.html
get-service | ConvertTo-Html -CssUri "SS64.css" > c:\services.html
Invoke-Item c:\services.html
Ref. http://ss64.com/ps/convertto-html.html

Running Powershell in Azure, I've fixed the problem by typing "exit" and the "enter" to create a new session.

Related

Check AD users' network share mapping with PowerShell

I tried using net use, net share, among others - none of which return the expected output. So instead, I'm modifying a script I found to see which network drives/shares are mapped to a user the script is pushed to. Then I go to my log file, look at the data, and determine if the account is set up properly. Here's the current script:
Get-WmiObject Win32_MappedLogicalDisk -computer $env:COMPUTERNAME | select name, providername
Out-File -filepath "\\*UNC filepath*\Mapped_Drives_$env:USERNAME$(get-date -Format _MM-dd-yy" # "HH.mm.ss" "tt).txt"
When I run it, the log file returns empty and I'm not sure why. I changed "Out-File -filepath" to "Start-Transcript" which isn't working the way I want it to either (with too much verbose output). It outputs fine in my PowerShell ISE with all the proper shares listed, but doesn't work when I navigate to the logged output. What am I missing?
You must pipe the output into the logfile
$logfile = "\\*UNC filepath*\Mapped_Drives_$env:USERNAME$(get-date -Format _MM-dd-yy" # "HH.mm.ss" "tt).txt"
Get-WmiObject Win32_MappedLogicalDisk | select name, providername | Out-File $logfile
On a more general note I'd use the commands to fix the mapped drives right there and then, instead of just writing them to a logfile for later inspection.

How to execute, "Run Advertised Programs" with PowerShell

I display all the available applications on the "Run Advertised Programs" using PowerShell.
$tpObject = Get-WmiObject -Namespace ROOT\ccm\Policy\Machine\ActualConfig -Class CCM_SoftwareDistribution `
| Select-Object -Property PKG_Name, PKG_PackageID
This part works fine.
My Question: How do I execute one of these apps using PowerShell. I tried,
$tpObject.ExecuteProgram($ID, $PackageID,$true)
Where I Substituted the $ID and $PackageID for the values discovered in the first step. The code to execute the app gave me an error. I think my syntax is incorrect.
Any advice would be greatly appreciated.
tks

Using Read-Host to output information from a script

I am trying to run a script against exchange to bring back all of the mailboxes a certain user has access to. I want to be able to input the usersname using read-host. I currently have this:
$username = Read-Host("Please enter users username")
#Enable Exchange cmdlets
add-pssnapin *exchange* -erroraction SilentlyContinue
Get-MailBox | Get-MailboxPermission -User $username | FL > C:\MailboxPermissions.txt
However, when I run this via powershell, it asks for the username, looks like it is starting to run the script, then powershell just exits and there is not data outputted
Any help would be greatly appreciated
Thanks for all the help
I finally figured it out and there were a couple of issues. It was to do with the result size. I added -resultsize unlimited:
$username = Read-Host("Please enter users username")
add-pssnapin *exchange* -erroraction SilentlyContinue
>Get-MailBox -resultsize unlimited | Get-MailboxPermission -User $username | FL > C:\MailboxPermissions.txt
It would also not work by running the .ps1 file as this was not run by admin, and it needs admin permissions to output to the location I want. Once I created a shortcut for it to run via the powershell.exe with admin credentials it is now working as expected.
The problem is that you are only out putting to the screen.
This means that when you run your script it will carry out the required action, print to screen and close the window immidiatly. In turn, this means you can't see the output.
As #DarkLite1 mentioned, you could output to a file.
Or, you could simply allow the console to wait before closing. This is done like this at the end of your code:
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
You may also need a Write-Host on the last action in your code snippet, I'm not entirely sure as I am not familiar with how Get-Mailbox works, but try it without first.
To summarize, You must keep the window open or print the results to file to actually see anything. The code you have currently will complete so fast you will never see any output.

Errors running remote powershell script with PsEcec.exe

I have a powershell script on a remote windows box that finds the folder pointed to by a junction. The contents of the script looks like this:
return fsutil reparsepoint query C:\foo\bar\junction_name | where-object { $_ -imatch 'Print Name:' } | foreach-object { $_ -replace 'Print Name\:\s*','' }
When I run this on the remote box, it executes as expected :)
However, when I try to run this remotely from my local machine:
C:\Users\foo>C:\pstools\PsExec.exe \\remote_server_name "powershell D:\bar\my_script.ps1"
I get errors:
PsExec could not start powershell D:\bar\my_script.ps1 on
remote_server_name: The filename, directory name, or volume label
syntax is incorrect.
Any ideas what this error is telling me (given that I can run the script directly on the remote box with no issues)?
Thx!
1- maybe you should avoid psexec and take advantage of powershell remoting
invoke-command -computername remote_server_name -scriptblock {. "D:\bar\my_script.ps1"}
2- if you want to keep psexec, look at the starting directory switch -w
PsExec.exe \\remote_server_name -w D:\bar "powershell -file my_script.ps1"
PS Remoting would be the best way to go here and I'd actually put up a good fight for opening up TCP/5985 on your machines. The minuscule security risk is, by far, worth the management benefits you'll get with it.
Worst case scenario use the WMI Win32_Process class. Something like this might work.
$wmiParams = #{
'ComputerName' = 'Somecomputer'
'Class' = 'Win32_Process'
'Name' = 'Create'
'Args' = 'fsutil reparsepoint query C:\foo\bar\junction_name > C:\temp.txt'
}
Invoke-WmiMethod #wmiParams
Get-Content \\somecomputer\c$\temp.txt | where-object { $_ -imatch 'Print Name:' } | foreach-object { $_ -replace 'Print Name\:\s*', '' }
I managed to get the following to work:
PsExec.exe \\remote_server_name powershell.exe D:\bar\my_script.ps1
However, the powershell session did not close as expected and remained in a hanging state after my script returned so calling it via cmd as detailed here seems to fix that:
PsExec.exe \\remote_server_name cmd /c "echo . | powershell.exe D:\bar\my_script.ps1"
Thanks for all of the suggestions...

Powershell 2: Unable to suppress warning message

I am making a cmdlet call to 'set-distributiongroup' in powershell 2. I am simply setting the value of the parameter 'hiddenFromAddressListsEnabled' to a pre-defined boolean value.
However, no matter what I try, it displays a warning message if the boolean assignment is not actually changing the current value of 'hiddenFromAddressListsEnabled'.
Here is the main command I'm invoking:
set-DistributionGroup -identity TestGroup `
-hiddenFromAddressListsEnabled=$true
Let's semantically define what I have above as 'command'.
Now, I've tried adding several different variants, all with proper line-continuation and syntax. Here are those variants:
command > $null
command 2> $null
command -ErrorAction:silentlycontinue
command -ErrorVariable $throwAway
command -WarningAction:silentlycontinue
command -WarningVariable $throwAway
$var = command
Regardless of various combinations of one or more of the above, I still get a yellow WARNING: message spit to output. Specifically, this:
WARNING: The command completed successfully but no settings of
'<xxxxxx>/Users/TestGroup' have been modified.
Any suggestions on a key concept I'm not understanding? I want the command to not produce this output, and I want it to silently continue if this occurs.
Thanks!!
I've been trying to suppress the warning messages when stopping a service:
WARNING: Waiting for service 'Service Description' to finish stopping...
The following worked for me:
Stop-Service $svc.Name -WarningAction SilentlyContinue
If it's just a warning that cause problem why don't you set in your script $WarningPreference variable ?
PS C:\> $WarningPreference='silentlycontinue'
PS C:\> Write-Warning "coucou"
PS C:\> $WarningPreference='continue'
PS C:\> Write-Warning "coucou"
AVERTISSEMENT : coucou
just bumped this topic when searching on the issue,
my case PowerShell v2 , only after setting
$WarningPreference = "SilentlyContinue"
Write-Warning "blah" - returned me nothing... the parameter on the command didn't changed much too on my end.
You may be hitting this bug: http://connect.microsoft.com/PowerShell/feedback/details/541500/warning-verbose-and-debug-streams-do-not-respect-action-preferences-the-way-they-should
Anyway, your command should look like:
Set-DistributionGroup -Identity TestGroup -HiddenFromAddressListsEnabled $true
Your command is wrong. Which is the the reason why you get a yellow error message. The command should look like:
Set-DistributionGroup -Identity TestGroup -HiddenFromAddressListsEnabled $true
Or
Set-Distributionaliste -Identity TestGroup -HiddenFromAddressListsEnabled:$true
But not
Set-DistributionGroup -Identity TestGroup -HiddenFromAddressListsEnabled=$true
I was getting the same problem with the Exchange Management Console in 2010. Problem is the EMC runs on PowerShell 2.0, which as stated before has some bugs around warning preferences.
I found a cheeky workaround was to run my script in a vanilla PowerShell 4.0 shell, and then import the EMC cmdlets and start a new remote PS session like so...
. 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'
Connect-ExchangeServer -auto
...then, -WarningAction:SilentlyContinue suddenly starts behaving itself.
You should try
Set-DistributionGroup -Identity TestGroup -HiddenFromAddressListsEnabled $true -WarningAction silentlyContinue
I bumped into same issue, the following command seems to do the job (PS 3.0) :
Stop-Service<or whatever command> $svc.Name -WarningPreference SilentlyContinue
Don't know exactly what difference it makes with -WarningAction, though.
Hope this helps !
If you invoke powershell versión 2.0, you should use "-WarningAction silentlyContinue". I was having the same issue, but in the script, if I invoke, for example "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -versión 2.0" , then you can use this parameter. I was trying on a scheduled task and using a ps1 script.
Try something like that:
PS C:\> {command} | Out-Null
For more Information: Technet: Out-Null