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

How to format date in a Powershell command

$
0
0

Hi,

I try to get the install date of installed software correctly. My command hat the date output not correctly as follow. How can I list "InstallDate" correctly in formatDD.MM.YYYY?

PS> Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | select DisplayName, InstallDate |Sort-Object InstallDate -descend

Output:

DisplayName                                             InstallDate
-----------                                             ------------
Smart Storage Administrator CLI                         20171212
Microsoft Silverlight                                   20171206

Best regards

Birdal


Improving Performance (remotely dcdiag, Start-Job, Substring,...)

$
0
0

Hello dear experts,

I am working on a customized version of 'ADHealthCheck' script by Sukhija Vikas (this link). I did quit a lot of modifications (adding another column, removing tqo columns), however I would like to also increase the performance.

So it is not possible to write the whole script here and ask for free modifications and I am not that type of guy to ask this, but instead I try to present the scrit in a friendly way so maybe you can point me where I am missing?

It does like this:

$DCServers = (Get-ADDomainController -Filter *).HostName foreach (DC) { # JOB 1 # $Job = start-job -scriptblock {Get-Service -ComputerName $DC -Name "Netlogon" $Status = Receive-job $Job # Process the Job and write to HTML # # JOB 2 # [array]$Diag= start-job -scriptblock {dcdiag /test:netlogons /s:$DC} $Status = Receive-job $Diag # Some process to see if DCdiag was Ok. (Replace,Trim,IF) # write to HTML # # JOB X # ....... # JOB 8 # ...... }

Some notes:

  • I have 8 jobs.
  • In these jobs I user text filters to find wether the task was successfull or not. (Replace all spaces, Trim, find the success,...)
  • All of thel are ran remotely on DC as examples above
  • There are 120 DCs.
  • The script gives the right report, it takes some times. 

What else I can do to speed up? Can I do some stupid things like:

  • Divide the entire array of DCs to a total of 3-4 subarrays. In that case I can have 3 arrays in which there are 40 DCs instead of an array of 120 DC. Is it possible? To call another Job, inside another Job. Something like nested jobs.
  • Remove variables to speed up? 

Any ideas would be interesting to hear.


Mahdi Tehrani | | www.mahditehrani.ir
Make sure to download my free PowerShell scripts:

Powershell - Remote CSV File

$
0
0

Trying to load a CSV file sitting on a remote PC into a datagridview. Getting access denied, I need to provide credentials somehow but can't seem to find the best way to do it. So far I have something like this...

$rows = Import-Csv -Path "\\servername\e$\path\file.csv" -Header Header1,Header2
$table = ConvertTo-DataTable -InputObject $rows
Update-DataGridView -DataGridView $datagridview1 -Item $table

This fails with access denied. Looking for a way to access this file on the remote server and load it into my datagrid.

Accessing multiple oracle databases from Powershell

$
0
0

Hello All,
This is my first post. I want to query multiple oracle databases inside powershell script
can you please help me to do it. I am successful in querying one database.

============================================================

This is what I use currently for single database query

#Function to Open connection to oracle DB

function Connect-Oracle{

        [CmdletBinding()]

        param(

            [string] $connectionString = $(throw "connectionString is required")

        )

  

$conn= New-Object Oracle.DataAccess.Client.OracleConnection($connectionString)

$conn.Open()

Write-Output $conn

}

#Create connection string with database settings

function Get-ConnectionString{

        [CmdletBinding()]

        param(

            [string]$user = "fdcdb",

            [string]$pass = "bistel",

            [string]$hostName = "apk0bistel-scan",

            [string]$port = "1521",

            [string]$sid = "apkbstl.tqs.com"

        )

$dataSource = ("(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST={0})(PORT={1}))(CONNECT_DATA=(SERVICE_NAME={2})))" -f $hostName, $port, $sid)

Write-Output ("Data Source={0};User Id={1};Password={2}" -f $dataSource, $user, $pass)

}

# Starts the connection

$conn = Connect-Oracle (Get-ConnectionString)

# Get connection state and Server version

"Connection state is {0}, Server Version is {1}" -f $conn.State, $conn.ServerVersion

function Get-DataTable{

        [CmdletBinding()]

        Param(

            [Parameter(Mandatory=$true)]

            [Oracle.DataAccess.Client.OracleConnection]$conn,

            [Parameter(Mandatory=$true)]

            [string]$sql

        )

$cmd = New-Object Oracle.DataAccess.Client.OracleCommand($sql,$conn)

$da = New-Object Oracle.DataAccess.Client.OracleDataAdapter($cmd)

$dt = New-Object System.Data.DataTable

[void]$da.Fill($dt)

return ,$dt

}

Powershell Test-Path of HKEY_USERS

$
0
0

Hello Folks,

I'm attempting to write a script that will update a non logged in users NTUSER.dat registry setting.

I load the hive with: REG load "hku\temp" c:\users\${username}\NTUSER.dat.  That occurs successfully, but when I attempt to do a test-path for a setting, that I know is there, it always returns false. For example:Test-Path "hku\temp\Software\Microsoft\Office"

In fact, I do a test-path on my current HKU setting, that I copied and pasted from registry editor copy key name, and that as well says false. Test-Path "HKEY_USERS\SID#\Software\Microsoft\Silverlight"

Can someone please provide some guidance?  Thanks in advance!!

How to run a script in an Office 365 environment

$
0
0

We would like to run this script: https://gallery.technet.microsoft.com/office/How-to-export-all-the-9870e78b/view/Discussions#content - to export a list of groups in Office 365 to a .CSV file.  Our apologies as we are new to scripting! 

We would appreciate help in understanding how to run the script:

1. We have attempted to run the script on a windows machine.  We are going to Powershell, entering the text from the script. We received two different error messages -

a) Access is denied. We are trying to export a list of groups for a 3rd party and we have multiple Office 365 accounts. We have a global admin account that we enter in the log in screen in order to get access for the 3rd party's Office 365 account. This is not accepted. Our own global admin account that we use on the machine works and we get access. Why can't we sign in using the 3rd party's global admin account?

b) We can't run scripts on the machine.  We followed the steps to enable scripts in the Registry Editor but we don't have the Ënabled  option under Windows Script Host/Settings. How do we enable scripts?

Once the above problems are solved, we will have an additional question  -

1) What level of administrator account can run this script? Will an Exchange Administrator role suffice?

Thanks very much for your help. 

Uninstalling Non MSI package Remotely from Multiple Computers

$
0
0

Looking for a powershell script to uninstall Non MSI package remotely from multiple computers

Eg: AnyDesk Non msi Application

Auditing for shared folders?

$
0
0
Is there any way to check if Auditing is enabled for shared folders with Powershell? The idea is to get list of all share folders on File server and if possible to have a columns to show if auditing is enabled etc.

PowerShell ISE -- Update-Help fails for WindowsUpdateProvider

$
0
0
update-help : Failed to update Help for the module(s) 'WindowsUpdateProvider' with UI culture(s) {nl-NL
} : Unable to retrieve the HelpInfo XML file for UI culture nl-NL. Make sure the HelpInfoUri property i
n the module manifest is valid or check your network connection and then try the command again.
At line:1 char:1
+ update-help
+ ~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (:) [Update-Help], Exception
    + FullyQualifiedErrorId : UnableToRetrieveHelpInfoXml,Microsoft.PowerShell.Commands.UpdateHelpComm
   and


Is there a solution for this problem?

Public Folder Send As Permissions

$
0
0

I'm trying to modify a script I found but i get an error: Cannot bind argument to parameter 'Identity' because it is null. Can someone please take a look at the below script and help me fix it?

FYI, i already have a list of all mail-enabled CN names in the format: CN=TEST-PF,CN=Microsoft Exchange System Objects,DC=conedison,DC=net

My environment: Exchange 2010 SP3 RU24

======================================================

$folderlist = "\\EX10UTIL\C$\TestScripts\PF\Input\DistinguishedName-One-Folder.txt"
$folders = get-content $folderlist
Import-Module ActiveDirectory

ForEach ($folder in $folders) {
  
 $ADobjects = Get-ADObject -Identity $folders |

 ForEach ($ADobject in $ADobjects) {

    Get-ADPermission $ADobject.distinguishedName |
       Where {$ADobject.ExtendedRights -like '*Send-As*' -and $ADobject.User.ToString() -ne 'CONED\Exchange SendAs Services'} | Select Identity,User

 }  | Export-Csv \\EX10UTIL\C$\TestScripts\PF\Reports\SendAs-Perm-For-Mail-Enabled-PFs.csv -NoTypeInformation
}


Piotr


How to change page file size without reboot?

$
0
0

I'm trying to use what's advised in https://blogs.technet.microsoft.com/heyscriptingguy/2013/03/17/weekend-scripter-use-powershell-to-configure-a-new-laptop/ to change the page file size programmatically. This works, however it has no effect until a reboot. If I do it via the UI, it has an effect immediately, as long as it's only a size increase.

I can observe that after running the Set-CimInstance PowerShell command, the value of (Get-CimInstance -Class Win32_PageFileUsage).AllocatedBaseSize doesn't change, however it *does* change when using the UI. Is there something else to force Windows to "commit" or "refresh" the new settings? Note that after running Set-CimInstance, the UI actually displays the new Initial and Maximum size values correctly, but it hasn't applied them, different to when using only the UI.


Is there a way to get the top 10 processes in Memory as Percent and not Bytes

$
0
0

Greetings all,

First time poster here.  I need to be able to run a script on a system that shows the top 10 processes in physical memory but as a percent not bytes.  Below is how I am listing the processes.  I have spent most of the day looking but have not found a scripts that can do this simple task.  Is there a way to do this?  Many thanks in advance for your help!

Get-Process |sort ws -Descending| select ProcessName, WS | select -First 10

v/r

Chris

Finding SID from file

$
0
0

I have an external hard drive where a bunch of different users have saved files, I need to get the SID for these users to help them assist with migrating the files to SharePoint Online.

Basicaly, what I want to do is extract the file authors SID from the file itself. Is there anyway to do this?

The users have never signed in on my computer and aren't connected to our AD so the SID is nowhere else to be found.

Thanks in advance!

Powershell script to get status of multiple service

$
0
0

Hi There,

Greeting!

I am new to powershell and Am looking out for a logic that, i have csv file which include hostname and services example below. In my case the count is 1500+

HostName,Service1,Service2,Service3

ASIA,Service a, Service b, Service c

APAC, Service d, Service f, Service e

Now i want a service status of APAC server which will passed as variable seperately and then it should check the csv file, then mapped the hostname in csv file and get the service name for checking the status.

For example

1) pass hostname to search in the csv file

2) if matched hostname get service name which is mapped to the hostname in csv file

3) now get the service details

Require your kind suggestion it would be very helpfull.

Thanks

Bash to Powershell script convert

$
0
0

I need to convert a bash script into powershell:

s#!/bin/bash

if [ $# -ne 1 ]; then echo "Usage:" echo ${0##*/}" " echo exit 1 fi

r=ss -ln6tp | grep -c ":::$1"

  if [ $r -ne 1 ]; then

  echo "Agent on port $1 is not listening."

  exit_code=2

else

  echo "Agent listening on port $1"

  exit_code=0 fi

exit $exit_code

I don't have experience with bash at all and my powershell knowledge is basic.

My idea for R varibale part:

$r = netstat -ta | Select-String ":$arg"
$r.count

If statement is not big problem, but Exitcode is the main problem for me here.
Any ideas please?


Get-CimInstance not finding all Event Logs in Win32_NTLogEvent

$
0
0

Afternoon. I have setup my event log to have this (Microsoft-Windows-PrintService/Operational) enabled. I'm using Windows 8.1. The event is triggered in event viewer (EventID 821) when I print.

When I run
Get-CimInstance -ClassName Win32_NTLogEvent -Filter "(LogFile like 'Microsoft-Windows-PrintService/Operational')" I get nothing back.

I have also tried Get-WmiObject -Class Win32_NTLogEvent -Filter "LogFile like 'Microsoft-Windows-PrintService/Operational'" and get nothing back.

Get-WinEvent -LogName Microsoft-Windows-PrintService/Operational returns successfully.
Is get-ciminstance not able to see this part of the Event Log?

Any guidance/help appreciated.

Thanks, Tim.

 

Cached UNC files?

$
0
0

We have a number of scripts that read an XML for data.

At the beginning of the scripts there is a line like:

[xml]$configFile = Get-Content '\\<server>\<share>\config.xml'

For years now, whenever I make a change to the XML file, the change is read into the script the next time the script runs.

This changed about a month ago. I made a change to the xml file and the scripts are using the old value which absolutely does not exist in the current xml file. The only conclusion I can come to is that the xml file has been cached somehow. I have checked and there are no offline files configured.

Any explanations?

Thanks

David Z

How to run a command line within a elevated cmd.exe launched by a VBScript.

$
0
0

I am looking for some assistance on how to create a Vb Script to run a command line within an elevated command prompt and that would prompt the administrator to log in using his credentials to run the commands. (If the user does not have the admin privileges). For instance, let's say I wanted to run this script below on a users machine. How would I go about opening this within an elevated command prompt using a VB script?

  Broken SCCM client

·         Open an elevated command prompt

ipconfig /flushdns

 nbtstat –R
 arp –d
ipconfig /registerdns

net stop winmgmt and answer Y when prompted

winmgmt /salvagerepository

net start winmgmt
%windir%\CCM\ccmrepair.exe

Need script to start/stop a web site by ID in IIS

$
0
0

Hell0 Guys,

I Need a powershell/bat script to start/stop a web site by ID in IIS for to allow for maintenance. Can you please share the script if you have it. Thanks



[Powershell] Is there a way to have a parameter as switch as well as string

$
0
0

hi,

I searched the internet on this. However, I couldnt find anything that would give me an answer to this.

Finally turning here for help. What I'm trying in powershell is as follows:

I created a script like this (please forgive me if i've made mistakes anywhere, i'm still learning powershell):

[CmdletBinding(PositionalBinding=$false)] Param( [switch]$Param1, [string]$Param2, )

For Param1, I can check in the script for true OR false values and perform some actions. But for Param2, I need to pass a string while using this (i.e. -Param2 <someString>) or else it throws an error. However, lets say, I want to pass it as a switch as well. So say, if the file is PSTest.ps1,

and I want to pass on the command line as :

Powershell -File PSTest.ps1 -Param1 -Param2

without passing any string value to Param2. I know we can pass a default value to a string. So if we don't pass the parameter -Param2, it would take the default value for Param2 that we define in script. Thats the thing. It should not take the default value unless I pass -Param2 (hence the switch). Also '-Param2 <someString>' should also work.
Is it possible to do such thing?

Hope I'm able to convey my question there. Thanks in advance.




Viewing all 15028 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>