Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all 15028 articles
Browse latest View live

Batch File for Disconnecting RemoteApp Session

$
0
0

We started using RemoteApp to login to an application but having to login and then logout of the Virtual Office is confusing for some users. We have multiple users using a shared computer (and windows account) so I want to create a batch file placed on the desktop that they can just double-click before leaving the computer. 

Equivalent to right-clicking the RemoteApp system tray icon and selecting Disconnect from XYZ Virtual Office.

I've read and respect the Posting Guideline sticky, so before I spend more time researching I just want to know if this is even possible?

Thank you.


How can I updater password of service account in Credential manager remotely using PowerShell?

$
0
0

Hi,

I can able to updater Cached Credential password on local machine using cmdkey.exe, however due to the limitation of cmdkey.exe it is not working remotely using PowerShell remoting. Can someone give me idea how can I achieve this programmatically.

Help With Data Input for Get-WinEvent -FilterXPath

$
0
0

Hello Hello.

I'm having some trouble getting the desired result when parsing event logs from the security log.  I've enabled windows auditing, and I'm attempting to parse the Access List data as seen  under "Accesses" In the log below.  Below that photo is the XML data view

I've gotten as far as being able to perform the following:

Get-WinEvent -FilterXPath "*[System[(EventID='4663')] and EventData[Data[@Name='AccessList']and (Data='%%1537
%%1537
%4423
		
		')]]" -LogName Security  -MaxEvents 1

I've had success with parsing the following log entry to gather when a file is opened/accessed by modifying the syntax, however, with multiple data entries, I can't seem to figure out the formatting to get it to work.

Get-WinEvent -FilterXPath "*[System[(EventID='4663')] and EventData[Data[@Name='AccessList']and Data='%%1538`r`n`t`t`t`t']]" -LogName Security  -MaxEvents 1

So my question is: how do I format my first string of text to get the desired logs for deleted files with auditing turned on? 

Thanks in advanced for anyone who can assist.


Vb Script print server rename

$
0
0

Hi guys

I'm setting up a new print server W8K and I would like to know if there's a way to change the name of the old server ex'\\printer01 with\\printer08 with a script and not having to re-install all the printers to all my clients. I've named my printer the exact name they had on my old print server only the server name has change. 

 

Thanks in advance

enums with duplicated entries

$
0
0

Hey, Scripting Guy!  Why do some public enums have duplicated entries?  That is, within a single enum, two or more entries with the same name and integer value.

I explored public enums to get a feel for common usage practices.  Found well over a thousand types where both IsPublic and IsEnum.  I do understand that just because something has the Public attribute, that doesn't mean I'm supposed to use it.  I'm just looking, thanks.

    $Assemblies = [AppDomain]::CurrentDomain.GetAssemblies() | where { $_.location -notlike $NULL }
    $AllEnums   = $Assemblies.getexportedtypes() | where { $_.IsPublic -and $_.IsEnum } | sort FullName

I Examined enums within $AllEnums:

function Show-Enums( $Enums ) {
    foreach ( $EnumObj in $Enums ) {
        $FullName = $EnumObj.FullName
        "$FullName"
        if ( [enum]::GetUnderlyingType( $FullName ).Name -eq 'uint64' ) {
            [enum]::GetValues( $FullName ) | % {
                ' {0,15:N0}  {1}' -f [uint64]$_, $_
            }
        } else {
            [enum]::GetValues( $FullName ) | % {
                ' {0,15:N0}  {1}' -f [int64]$_, $_
            }
        }
    }
}

Show-Enums ($AllEnums) > .\temp.txt

I was able to see that when the designers make the underlying type of an enum to be one of the unsigned types, the values are usually bit masks, and when the underlying type is signed the values are usually (but not always) indexes.  Also, that some underlying types are 32-bit and some are 64-bit (didn't notice any 8- or 16-bit).

But I did encounter a few dozen instances of what is either an anomaly or a fiendishly clever practice, and so I've come to you for instruction.

The enums in question have duplicated entries.

So for example if I call the above function as follows:
    Show-Enums ( [microsoft.powershell.executionpolicy], [windows.messageboximage] )

The output is:

Microsoft.PowerShell.ExecutionPolicy
               0  Unrestricted
               1  RemoteSigned
               2  AllSigned
               3  Restricted
               3  Restricted
               4  Bypass
               5  Undefined
System.Windows.MessageBoxImage
               0  None
              16  Hand
              16  Hand
              16  Hand
              32  Question
              48  Warning
              48  Warning
              64  Asterisk
              64  Asterisk

Can you explain what is happening here?  Anomaly or subtlety?

Here is my complete list of enums with duplicate entries, returned by a script I cobbled together.

VERBOSE: In [Microsoft.Management.Infrastructure.CimSubscriptionDeliveryType] Push is duplicated
VERBOSE: In [Microsoft.Management.Infrastructure.Options.CimCallbackMode] Report is duplicated
VERBOSE: In [Microsoft.Management.Infrastructure.Options.CimPromptType] Normal is duplicated
VERBOSE: In [Microsoft.Management.Infrastructure.Options.CimResponseType] None is duplicated
VERBOSE: In [Microsoft.PowerShell.ExecutionPolicy] Restricted is duplicated
VERBOSE: In [Microsoft.VisualStudio.Text.Differencing.WordSplitBehavior] CharacterClass is duplicated
VERBOSE: In [Microsoft.WSMan.Management.WSManEnumFlags] WSManFlagHierarchyDeep is duplicated
VERBOSE: In [System.ComponentModel.Design.SelectionTypes] Normal is duplicated
VERBOSE: In [System.Diagnostics.Eventing.Reader.StandardEventKeywords] AuditFailure is duplicated
VERBOSE: In [System.Diagnostics.PerformanceCounterPermissionAccess] Browse is duplicated
VERBOSE: In [System.Diagnostics.Tracing.EventKeywords] WdiContext is duplicated
VERBOSE: In [System.DirectoryServices.AuthenticationTypes] SecureSocketsLayer is duplicated
VERBOSE: In [System.Drawing.Drawing2D.HatchStyle] Horizontal is duplicated
VERBOSE: In [System.Drawing.Drawing2D.PathPointType] Bezier3 is duplicated
VERBOSE: In [System.Drawing.Imaging.EmfPlusRecordType] EmfMin is duplicated
VERBOSE: In [System.Drawing.Imaging.PixelFormat] DontCare is duplicated
VERBOSE: In [System.Drawing.RotateFlipType] RotateNoneFlipNone is duplicated
VERBOSE: In [System.LoaderOptimization] DomainMask is duplicated
VERBOSE: In [System.Management.Automation.DSCResourceRunAsCredential] Default is duplicated
VERBOSE: In [System.Management.Automation.Language.TokenFlags] BinaryPrecedenceMask is duplicated
VERBOSE: In [System.Management.Automation.PSCredentialUIOptions] Default is duplicated
VERBOSE: In [System.Management.Automation.SigningOption] AddFullCertificateChainExceptRoot is duplicated
VERBOSE: In [System.Net.HttpStatusCode] MultipleChoices is duplicated
VERBOSE: In [System.Net.NetworkInformation.IPStatus] DestinationProhibited is duplicated
VERBOSE: In [System.Net.Sockets.AddressFamily] NS is duplicated
VERBOSE: In [System.Net.Sockets.ProtocolFamily] NS is duplicated
VERBOSE: In [System.Net.Sockets.ProtocolType] Unspecified is duplicated
VERBOSE: In [System.Net.Sockets.SocketOptionName] Debug is duplicated
VERBOSE: In [System.Net.TransportType] Udp is duplicated
VERBOSE: In [System.Reflection.EventAttributes] RTSpecialName is duplicated
VERBOSE: In [System.Reflection.MethodAttributes] ReuseSlot is duplicated
VERBOSE: In [System.Reflection.MethodImplAttributes] IL is duplicated
VERBOSE: In [System.Reflection.TypeAttributes] NotPublic is duplicated
VERBOSE: In [System.Runtime.InteropServices.CALLCONV] CC_MSCPASCAL is duplicated
VERBOSE: In [System.Runtime.InteropServices.ComTypes.CALLCONV] CC_MSCPASCAL is duplicated
VERBOSE: In [System.Security.AccessControl.AceType] SystemAlarmCallbackObject is duplicated
VERBOSE: In [System.Security.AccessControl.FileSystemRights] ReadData is duplicated
VERBOSE: In [System.Security.AccessControl.RegistryRights] ReadKey is duplicated
VERBOSE: In [System.Security.Cryptography.CngKeyOpenOptions] None is duplicated
VERBOSE: In [System.Security.Cryptography.X509Certificates.X509ContentType] Pfx is duplicated
VERBOSE: In [System.Security.Principal.WellKnownSidType] WinBuiltinTerminalServerLicenseServersSid is duplicated
VERBOSE: In [System.Windows.Forms.AccessibleStates] Mixed is duplicated
VERBOSE: In [System.Windows.Forms.ArrangeDirection] Left is duplicated
VERBOSE: In [System.Windows.Forms.Keys] Return is duplicated
VERBOSE: In [System.Windows.Forms.MenuGlyph] Arrow is duplicated
VERBOSE: In [System.Windows.Forms.MessageBoxIcon] Hand is duplicated
VERBOSE: In [System.Windows.Forms.ScrollButton] Min is duplicated
VERBOSE: In [System.Windows.Forms.TextFormatFlags] GlyphOverhangPadding is duplicated
VERBOSE: In [System.Windows.Input.Key] Return is duplicated
VERBOSE: In [System.Windows.Media.BitmapScalingMode] Linear is duplicated
VERBOSE: In [System.Windows.Media.Imaging.BitmapCacheOption] OnDemand is duplicated
VERBOSE: In [System.Windows.MessageBoxImage] Hand is duplicated
VERBOSE: In [System.Xml.XPath.XPathResultType] String is duplicated
VERBOSE: In [Windows.UI.Notifications.TileTemplateType] TileSquare150x150Image is duplicated

how can I validate IIS application pool identity after updating password using PowerShell?

$
0
0

Hi,

I have written PowerShell script to update IIS application pool identity password in PowerShell. When I am doing through Powershell script is accepting when we give wrong password as well. After updating password I recycled the application pool and it working good when I updated with wrong password. How can I validate that application pool identity password updated with the correct on or not. I know one solution to validate against AD before updating in IIS, but that didn't meet my requirement.

Can someone please help me to achieve this through PowerShell?

Locale settings in windows using Command Line.

$
0
0
how to change the locale in windows using command line

receive-job output to variable

$
0
0

Hi, 

How do I get the receive-job output for a specific job into a variable ? 

$var = receive-job -Name jobname 

does not seem to work. 

Thanks 


Errors on Get-ADUSER

$
0
0

# Get-ADUser -filter * -Properties * | Where-Object {$_.employeeType -ne $null} | ? {$_.employeeType -eq 'S'} | Select-Object SamAccountName Get-ADUser -filter * -Properties * | ? {$_.employeeType -eq 'S'} | Select-Object SamAccountNameI

I get and error:

Get-ADUser : Cannot find the requested object.
At line:4 char:1
+ Get-ADUser -filter * -Properties *   | ? {$_.employeeType -eq 'S'} |  ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-ADUser], CryptographicException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.Security.Cryptography.CryptographicException,Microsoft.ActiveDirectory.Management.Commands.GetADUser

This error on internet:

https://www.reddit.com/r/PowerShell/comments/4czkb1/getaduser_cannot_find_the_requested_object/

But I have patched Powershell and even when to Version 5. Same issue.

vbscript to run netsh

$
0
0

I am trying to run a netsh command within a vbscript. It runs, but doesn't do that I want it to. The code is supposed to create a firewall exception for a windows management instrumentation (WMI).

command : netsh advfirewall firewall set rule group="windows management instrumentation (WMI)" new enable=Yes

above command runs fine when I invoke it directly from the cmd.exe

Here is the code:

Function Firewall_Exception_WMI()

Dim WShShell

Set WShShell = WScript.CreateObject ("WScript.Shell")
WShShell.run "%comspec% /c netsh advfirewall firewall set rule group=""windows management instrumentation (WMI)"" new enable=Yes", 1, True

End Function

Script for Outlook maintenanceand PST file repair

$
0
0

I am looking to do a script for the following

  1. Repair pst file, no backup, repeat until no errors
  2. Archive sent items older than 60 days to certain path
  3. Archive deleted items older than 60 days to certain path
  4. Compact pst file
  5. send log of this to email

I would like to get this done without the use of commercial utils and just nice clean scripting

Jobs inside job ~ PowerShell

$
0
0

I wrote a script where I want to break one file into small parts and process all small parts same time to get better performance. I am using for loop inside a job and creating child jobs from there. While executing the script sometimes all small parts are processing fine. Sometimes 2 of them processing for same source. Any idea why this is happening?

*************************************************************************************************

Script 1: Master.ps1

Start-Job -filepath "sc_8200.ps1"

*************************************************************************************************

Script 2: sc_8200.ps1

$files = Get-ChildItem "\Desktop\sc" -Filter "splitlog*" | Select-Object -Expand fullname
foreach($file in $files)
{
Start-Job -Name $file -filepath "\Desktop\sc\sc_8200_child.ps1" -ArgumentList $file
}

*************************************************************************************************

Note: "splitlog" is name of small files.

*************************************************************************************************

Script 3: sc_8200_child.ps1

param (
    [string]$path
 )
Function Test()
{
$contents = Get-Content $path
foreach($content in $contents)
{
$temp = $path.SubString(0,$path.Length-4)
$outputfile = $temp+"_O.txt"
Get-ChildItem $content -Recurse -include *.* | Select-Object -Expand fullname >> $outputfile
}
}

Test

*************************************************************************************************

Replace string in the log file

$
0
0

Hello everyone,

I really suck with Powershell scripting. I'm trying to replace string in a log file, I was able to replace one part of the string that I want to replace with and the remaining part I just can't figure it out.

I have several string with &X-ARR-LOG-ID=xxxxxxxxxxxxxx (the xxx are 36 characters in length that including number, letter, and hyphen. It generates randomly  by IIS), I was able to replace &X-ARR-LOG-ID= but can't replace for part after =. 

I would really appreciate if anyone can help me with this.

Thanks in advance.



dtng




Get-Winevent from multiple logs

$
0
0

Hi,

Is it possible to grab events from two logs in the same query? I am converting these to html and need them to be in the same table.

Get-WinEvent  -FilterHashTable @{LogName="System"}  | ?{$_.LevelDisplayName -eq "Critical" -or $_.LevelDisplayName -eq "Error"} | Select @{Name="Time";Expression={$_."TimeCreated"}},@{Name="Level";Expression={$_."Level"}}

Get-WinEvent  -FilterHashTable @{LogName="Application"}  | ?{$_.LevelDisplayName -eq "Critical" -or $_.LevelDisplayName -eq "Error"} | Select @{Name="Time";Expression={$_."TimeCreated"}},@{Name="Level";Expression={$_."Level"}}

I have tried the below and nothing gets pulled unless I run them separately.

Get-WinEvent  -FilterHashTable @{LogName="System","Application"}

Get-WinEvent  -FilterHashTable @{Listlog="*"}

Get-WinEvent  -Listlog *

Thanks

Chat Application and Script Errors

$
0
0

Hello All,

We are integrating LiveChat application in PowerShell UI using Webbrowser control, but the Webbrowser control shows script errors. If we say "Yes" to errors, nothing works.

We are using below code:

<!-- Start of LiveChat (www.livechatinc.com) code -->
<script type="text/javascript">
window.__lc = window.__lc || {};
window.__lc.license = 8351171;
(function() {
  var lc = document.createElement('script'); lc.type = 'text/javascript'; lc.async = true;
  lc.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'cdn.livechatinc.com/tracking.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(lc, s);
})();
</script>
<!-- End of LiveChat code -->

We have also tried using iFrame to load script, but to no avail:

<iframe src="https://secure.livechatinc.com/licence/8351171/open_chat.cgi" width="400px" height="400px"> 
</iframe>

We have heard that IE will always throws script errors when Webbrowser control is used. Can someone please help us fix this please?

Thank you very much for all your help.

Mark.


How do i run the powershell script on the newly opened window with domain admin account?

$
0
0

Guys, I need to run the powershell script using domain admin account. the below script would open the powershell window with domain admin credentials. But the script is not running on that window. How do i run the script on the newly opened powershell window with domain admin account?

$username = 'Domain\AdminUsername'
$password = 'Password'

$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword
Start-Process powershell.exe -Credential $credential

if((Test-connection -ComputerName $computers -Quiet) -eq $true)
{
}
els
{
}

Convert date and time format to UK

$
0
0

I have a script by Justin Beeden that will retrieve email message stats and output them to a file. The problem with the script is that I get the following error when I try to run it:

Cannot convert value "20/10/2016" to type "System.DateTime". Error: "String was not recognized as a valid DateTime."
At C:\Users\myaccount\Desktop\Exchange Powershell\GetMessageStatsToFile.ps1:45 char:1
+ $outfile_date = ([datetime]$rundate).tostring("yyyy_MM_dd")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastParseTargetInvocationWithFormatProvider

The part of the script that it is referring to is the following:

 

$rundate = $(Get-Date).toshortdatestring()
$startdate = $((Get-Date).adddays(-$DaysToGoBack)).toshortdatestring()

$outfile_date = ([datetime]$rundate).tostring("yyyy_MM_dd")
$outfile = "$DaysToGoBack" + "DaysMessageStats_" + $outfile_date + ".csv"

$dloutfile = "DistListStats_" + $outfile_date +".csv"

Any assistance with this would be appreciated.

Thanks and regards

Scott



Accessing MS Access database from PowerShell

$
0
0

I'm working on my first real PowerShell script. I'm converting an old VBScript to PowerShell. The script uses an Access database to track computer information. In looking for information on how to connect to the database, I'm coming across a number of methods for accomplishing this: ADO, OLEDB, ODBC. Which is the best for use with PowerShell 5 on Windows 10? Can I access it via SQL commands even though I'm not using SQL server? So many of the threads I find are nearly ten years old, and I don't want to use an out-of-date method.

Thank you.

Counting instances of WMIMonitorID when no monitors are attached

$
0
0

According to this TechNet article, I can find out if a computer has any tape drives installed by querying Win32_TapeDrive and accessing the .Count property of the returned SWbemObjectSet like this:

strComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") Set colItems = objWMIService.ExecQuery("Select * from Win32_TapeDrive") Wscript.Echo colItems.Count

This works great for tape drives, but crashes with error 0x8004100C SWbemObjectSet: Not supportedwhen you attempt to query WMIMonitorID on a system with no monitors attached:

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\ROOT\WMI")
Set colItems = objWMIService.ExecQuery( "SELECT * FROM WMIMonitorID")
Wscript.Echo "Count: " &  colItems.count

Is there a way to determine if when there isn't a monitor attached besides using On Error Resume Next? I don't want to ignore or write an error handler for every possible WMI error just to avoid this one error.

For bonus points, can anyone explain why I can .Count an empty SWbemObjectSet when it is Win32_TapeDrive, but not when it is from WMIMonitorID? Is it due to one being in the cimv2 namespace while the other is in the WMI namespace?


Tim

Transcripts run amok

$
0
0

Hey Scripting Guy,

When we start PowerShell or PowerShell ISE, a transcript file is automatically created in a folder under the user's Documents directory. In fact, we get a new folder for every day, and users now have hundreds of such folders polluting their Documents folder, which is a problem. To be clear, this behavior is unrelated to Start-Transcript, and in fact happens upon PowerShell startup before any cmdlets have been called.

I've found the four profiles using $Profile | fl * -force, and tried adding $Global:TRANSCRIPT = "C:\logs" to each one, but that doesn't change this behavior.  My guess is there is some Windows 10 system setting somewhere that is causing this behavior, but so far I've been unable to locate it. 

Can you shed some light on how to suppress this "automatic" transcripting to the Documents directory?

Much Appreciated,

Erik

Viewing all 15028 articles
Browse latest View live


Latest Images