Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

Stagger Schedule Task Triggers

$
0
0

I'm trying to create a powershell script that will create scheduled tasks to reboot a list of servers weekly. I was wondering if there was a way to change the script so that when the scheduled tasks are created, the time that is assigned as the trigger for each task is staggered, so that way the servers aren't all scheduled to reboot at the same time. This is what my script looks like so far,

$List=Get-Content 'c:\Temp\SvrList.txt'
Foreach ($server in $List)
{
Invoke-command -ComputerName $server -scriptblock {
$Sta = New-ScheduledTaskAction -Execute c:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Argument 'restart-Computer -force'
$Stt = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Sunday -At 11pm
Register-ScheduledTask SundayReboot -Action $Sta -Trigger $Stt -User SYSTEM -Force -RunLevel Highest}
}
I'd like it so that they're scheduled to reboot around 2 minutes after each other. I appreciate any help you can offer, thanks!


COM Interfaces

$
0
0

I have a third party COM server API that I would like to use in PowerShell. I can use it in C#/Visual Studio, the types are recognized. However in PowerShell I cannot make it work. If I use New-Object - ComObject to instantiate the entry point, it is of type System.__ComObject. If I use the Interop (Add-Type -Path <Interop.dll>),  I get an error that there is no appropriate constructor.

Opening the interop in ILDASM, I see that entry point is defined as an interface. So the error from PowerShell makes sense, however why does it work in the C# Console App. The maker of the API only gives a C# example. Opening the tlb in OLEViewer, the same call is a coclass that implements an interface, the coclass itself has no members.

I do not understand enough about COM interop or the RCW to see why C#/Visual Studio can interpret the types however Powershell cannot.

Logon rds application vs. Logon Windows Server GUI

$
0
0

Hi,

I installed rds on a Windows Server 2016 and a Remote Desktop Application (exe)

User are in remote desktop user group.

The user is allowed to start an rds application through a rdp file from a client  computer.

The User is not allowed to  Logon to the desktop of the server.

I need a script/ mechanism which check's weather (1) the User logon via starting  my application or (2) logon on Windows desktop.
In Case the user starts to logon the desktop (2) if have to refuse/stop/hinder the logon

(i see, that in case the user logon starting my application(1), rdshell.exe ist running)
Perhaps there are other, easier indicators for deciding where the Logon comes from.

Any ideas?

Thank you in advanced


Issue with wildcard search in get-adcomputer

$
0
0

I am trying to perform a search for computers in my domain that end with lab## (ex/ lab02, lab03, etc) and I am having issues getting the filter to work. I can run the filter as

get-adcomputer -searchbase $oubase -properties Name -fitler {Name -Like "*lab*"}

But I need to have the last 2 places be numeric as well {*lab[0-9][0-9]}. This does not work at all and I have tried several variants with no success. How would I go about constructing this statement to work. Any advice or information would be greatly appreciated.

Get Stale Computer Records - Need help to improve the script

$
0
0

Hi Experts,

First of all, i am beginner of power-shell and as per my understanding i wrote script by doing googling for one of requirement in my company, but i think it can be compact by reducing duplicate steps,

Here i need your expert advice or help to review and modify script in proper way.

Requirement is:

1. Get Stale computer accounts - not logged-in from last 45 days. (excluding few OU's)

2. Check ping and DNS lookup and sort data based on the status e.g. Live.csv, RTO.csv, Unresolved.csv.

3. Move unresolved computers to stale OU and disable.

4. Send mail with attachment of 3 files mentioned in step no. 2

Note: For Live & RTO computers, need to captures DNS record time stamp, which will help to identify DNS record type e.g. Static or Dynamic

My power-shell code is below and its working fine but it is bit lengthy:

######Remove Exsisting Files###########

Remove-Item C:\temp\test\O*.csv -Force
Remove-Item C:\temp\test\SendOnMail\U*.csv,C:\temp\test\SendOnMail\O*.csv -Force

####Variables##############
$DaysInactive = 45

$time = (Get-Date).Adddays(-($DaysInactive))

$inactivecomp = 'C:\temp\test\SendOnMail\StaleComputer_NotLoggedInLast45Days.csv'

$StaleComputers = (Import-Csv C:\temp\test\StaleComputer_NotLoggedInLast45Days.csv).Name
$Online = "C:\temp\test\Online.csv"
$RTO = "C:\temp\test\OfflineResolved.csv"
$UnResolved = "C:\temp\test\SendOnMail\UnResolved.csv"

#####Get-AD Computers that have not been logged-in from last 45 days######

Get-ADComputer -Filter {( LastLogonTimeStamp -lt $time)} -Properties LastLogonTimeStamp | where-object {($_.DistinguishedName -notlike "*OU=Corpo*") -and 

($_.DistinguishedName -notlike "*OU=Project1*") -and ($_.DistinguishedName -notlike "*OU=Project2*")} |
select-object Name,DistinguishedName,DNSHostName,@{Name="LastLogon"; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp)}} | sort -Property LastLogon | 

export-csv $inactivecomp -notypeinformation -Force;

#################################

Start-Sleep -s 30

#####Check DNS Lookup & Ping ##################

ForEach ($Computer in $StaleComputers) 
{
Try
{
$DNS = [System.Net.Dns]::GetHostEntry($Computer)
If (Test-Connection $Computer -Count 2 -ErrorAction SilentlyContinue) 
{
"$Computer,$($DNS.HostName),$($DNS.AddressList[0].IPAddressToString),ONLINE" | Out-File -FilePath $Online -Append
}
Else
{"$Computer,$($DNS.HostName),$($DNS.AddressList[0].IPAddressToString),OFFLINE" | Out-File -FilePath $RTO -Append
}
}
Catch
{"$Computer,Could not resolve " | Out-File -FilePath $UnResolved -Append
}
}

###########################

Start-Sleep -s 30

#####Get-DNS record to identify Static & Dynamic Records - For RTO Computers######

$OfflineResolved = (Get-Content -Path C:\temp\test\OfflineResolved.csv | Select -skip 0 | ConvertFrom-Csv -Header Name -Delimiter ",").Name
$OfflineResults = @()

ForEach ($OffComputers in $OfflineResolved){

$OfflineResults += Get-DnsServerResourceRecord -ComputerName server1 -ZoneName test.com -RRType A -Name $OffComputers -ErrorAction Ignore | select-object -

Property Hostname,@{Name='RecordData';Expression={$_.RecordData.IPv4Address}},RecordType,TimeStamp
}

$OfflineResults | Export-Csv -Path C:\temp\test\SendOnMail\OfflineResolved_Computers.csv


########################

Start-Sleep -s 30

#####Get-DNS record to identify if its Static or Dynamic Records - For Online Computers####

$Online = (Get-Content -Path C:\temp\test\Online.csv | Select -skip 0 | ConvertFrom-Csv -Header Name -Delimiter ",").Name
$OnlineResults = @()

ForEach ($OnlineComputers in $Online){

$OnlineResults += Get-DnsServerResourceRecord -ComputerName Server1 -ZoneName test.com -RRType A -Name $OnlineComputers -ErrorAction Ignore | select-object -

Property Hostname,@{Name='RecordData';Expression={$_.RecordData.IPv4Address}},RecordType,TimeStamp
}

$OnlineResults | Export-Csv -Path C:\temp\test\SendOnMail\Online_Computers.csv


#######################

Start-Sleep -s 30

###Get all files for attaching in mail###########

[array]$attachments = Get-ChildItem "C:\temp\test\SendOnMail\" *.*

#####Send mail with required data attached in mail#########


$To      = "xyz@test.com"
$From    = "Do-NOT-Reply@test.com"
$smtpserver  = "192.4.24.173"
$Subject = "Stale Computer Report"
$Body = "<p>Hi Team,</p>"
$Body += "<p>Please refer attached report for stale computer account that have not been logged-in from last 45 days.</p>"
$Body += "<p>Kindly verify records and delete it frm stale OU and upload report on SharePoint</p>"
$Body += "<p><strong>Regards,</strong></p>"
$Body += "<p>Windows Team</p>"



Send-MailMessage -From $From -To $To  -Subject $Subject -SmtpServer $smtpserver -Attachments $attachments.fullname -BodyAsHtml $Body

####Moving Stale Computer To Stale OU##########

Start-Sleep -s 30

#####Move Unresolved Computers To Stale OU#######

$UnResolvedMove = (Get-Content -Path C:\temp\test\SendOnMail\UnResolved.csv | Select -skip 0 | ConvertFrom-Csv -Header Name -Delimiter ",").Name
$TargetOU = "OU=Stale_Comp_OU,OU=Test,DC=test,DC=com"


Foreach($DisabledOU in $UnResolvedMove){


Get-ADComputer $DisabledOU | Move-ADObject -TargetPath $TargetOU
}



#######################



Start-Sleep -s 30



###Disable Unresolved AD Computers#####



Get-ADComputer -SearchBase $TargetOU -Filter * | Disable-ADAccount



#######End Of Script##################



Adding an image as an overlay to an existing image

$
0
0
Hi All,

One of my customers is looking towards adding a branded screen saver to their fleet. I have their corporate logo as a PNG with transparency.

Rather than working with a fixed set of static images that we would have added the PNG to ahead of time... I had the idea to suck down Microsoft's spotlight images, add the overlay to those, and then use the modified image/s as a part of the standard Windows slideshow screensaver. Thus the screen savers dynamically change day to day and always feel fresh and new.

Pretty sure I am across what I need to do to access the source images, but where I am stuck on is adding the corporate logo to these images.

Found a number of examples online of how to use powershell to add a text based overlay/watermark... But nothing on how to insert one image into another.

Is it possible to accomplish this in powershell? To add one image to a specified position on another image?
If it is possible would the transparency of the logo be maintained or would it be replaced with white space?
Or would this require the use of third party tools?

Get output back from previous command in pipeline

$
0
0

I've been trying to get a output table sorted nicely but haven't found a good way of doing it. Maybe someone here already knows a trick to help? 

Get-VM can list a list of VMs.

Get-VMHost can list what host the VM is running on. So if I run the following, I would get a list of hosts, that run all the VMs:

Get-VM | Get-VMHost

This is all good, but when list is long, you don't know which VM is really running on which host that returned as the Get-VMHost only returns a list of hosts, which has no association to the VMs. So what I would like is to have a list of both VM and Host names. I've tried -outvariable and -pipelinevariable from the Get-VM but none worked properly. Maybe I missed something? 

as an example I did:

get-vm -outvariable ds | get-vmhost | ft $ds.name,name

Browsing a webpage

$
0
0

My PS includes the following to get some data on the webpage. It stopped working but the webpage support IE7 and above. Is there a way to fix it ? Thanks.

$ie = New-Object -ComObject internetexplorer.application
$ie.Navigate('https://web.tmxmoney.com/earnings_cal.php')
$ie.Visible = $true


Powershell VS sql DB2

$
0
0

hi folks, is anyone know any way how to query sql DB2 on Aix system Via Powershell?,10x

Delete files from specific folder and older than X days

$
0
0

Hello guys,

I'm trying to create a script that searches and delete files older than 2 days inside 2 different Root Folders' subfolders with Specific name. So far, what I did is this script below, but it is not working :(

$limit = (Get-Date).AddDays(-2)
$paths = "D:\work\AppLog1,G:\Logs\AppLog1" -split ','

#Delete files from cdatalogs folder
foreach($path in $paths)
{
        Get-ChildItem -Path $path -File -Recurse | where { $_.LastWriteTime -lt $limit -and $_.FullName -contains "cdatalogs"} | Remove-Item
        Write-Host "Files from $path removed"
}

I don't get any error, but no file is deleted when I run the script.

Does anyone can help me, please?

Thank you!
Ney Santos


 


Not able to create folder inside C:\ClusterStorage

$
0
0

I ran this command as admin also but giving same error every time 

PS C:\WINDOWS\system32> mkdir C:\ClusterStorage\Volume1
mkdir : Access to the path 'Volume1' is denied.
At line:1 char:1
+ mkdir C:\ClusterStorage\Volume1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (C:\ClusterStorage\Volume1:String) [New-Item], UnauthorizedAccessExcep
   tion
    + FullyQualifiedErrorId : CreateDirectoryUnauthorizedAccessError,Microsoft.PowerShell.Commands.NewItemCommand

Help with more or out-host -paging

$
0
0

Hello,

     I tried to use more or out-host -paging in my command in the PowerShell ISE, but neither of them working.

For example the out-host -paging gave me the following error message

 

PS HKLM:\system> get-process -name vb* | Get-Member | out-host -Paging

out-lineoutput : The method or operation is not implemented.
At line:1 char:1
+ get-process -name vb* | Get-Member | out-host -Paging
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [out-lineoutput], NotImplementedException
    + FullyQualifiedErrorId : System.NotImplementedException,Microsoft.PowerShell.Commands.OutLineOutputComm 
   and


I wonder if anyone may have a solution on how the see page of the results.

Many Thanks!


Student at Georgia Tech

Solved - How to take ownership and change permissions for blocked files and folders in Powershell

$
0
0

Hello,
I was trying to take ownership & fix permissions on Home Folder/My Documents structures, I ran into the common problem in PowerShell where Set-Acl & Get-Acl return access denied errors. The error occurs because the Administrators have been removed from file permissions and do not have ownership of the files,folders/directories. (Assuming all other permissions like SeTakeOwnershipPrivilege have been enabled.

I was not able to find any information about someone successfully using native PS to resolve the issue.  As I was able to solve the issues surrounding Get-Acl & Set-Acl, I wanted to share the result for those still looking for an answer.
----
Question: How do you use only Powershell take ownership and reset permissions for files or folders you do not have permissions or ownership of?
----

Problem: 
Using the default function calls to the object fail for a folder that the administrative account does not have permissions or file ownership. You get the following error for Get-Acl:

PS C:\> Get-Acl -path F:\testpath\locked
Get-Acl : Attempted to perform an unauthorized operation.+ get-acl <<<<  -path F:\testpath\locked+ CategoryInfo          : NotSpecified: (:) [Get-Acl], UnauthorizedAccessException+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetAclCommand

If you create a new ACL and attempt to apply it using Set-Acl, you get:

PS C:\> Set-Acl -path F:\testpath\locked -AclObject $DirAcl
Set-Acl : Attempted to perform an unauthorized operation.
At line:1 char:8+ Set-Acl <<<<  -path "F:\testpath\locked" -AclObject $DirAcl+ CategoryInfo          : PermissionDenied: (F:\testpath\locked:String) [Set-Acl], UnauthorizedAccessException+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.SetAclCommand

Use of other functions like .GetAccessControl will result in a similar error: "Attempted to perform an unauthorized operation."

How do you replace owner on all subcontainers and objects in Powershell with resorting to external applications like takeown, icacls, Windows Explorer GUI, etc.?

Tony

Is -ea a parameter?

$
0
0

Hello,

    I tried to understand what -ea is ? For example, I have

Get-Process $proc -EA 0 

    I know that $proc is a variable and its value is being passed to the Get-process.

   I try to find what -EA is ? I thought it may be an alias but it is not there when I tried to look for alias named EA in Get-help alias. So I try to ask the forum if someone can help me to figure out -ea. 


Student at Georgia Tech

access the mouse battery by powershell

$
0
0

Hi

I'm trying to know the battery status of a keyboard and a logitech mouse in order to be able to monitor it externally (zabbix).

I can't find it for WMI. Any idea how to access the mouse battery by powershell?

Thanks


Using Icons in Powershell Scripts

$
0
0

Hi there.

I am creating a powershell script that will execute a long job and I am referencing the "System.Windows.Forms.NotifyIcon" to show in the task tray when the script has finished. The issue I'm having is using the "System.Windows.Forms.NotifyIcon.Icon" property to reference an icon file. Now with this script being portable I would like to know if it is possible to reference an icon within a .DLL or .EXE instead of having to extract and copy the icon file with the script. I was hoping to use the icons within Shell32.DLL. I would think this is possible since other built-in Windows applications are capable of doing this e.g. Explorer.exe. Any ideas as I cant seem to find an answer on the web.


Any idea how to do with PowerShell 7 (.NET core 3)?.

$
0
0

Any idea how to do with PowerShell 7 (.NET core 3)?.  This code works with Windows PowerShell 5.1 but when I try to port this to PowerShell 7 (Preview 6) I get this error:

Add-Type: (9,23): error CS1069: The type name 'Icon' could not be found in the namespace 'System.Drawing'. This type has been forwarded to assembly 'System.Drawing.Common, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' Consider adding a reference to that assembly.
        public static Icon Extract(string file, int number, bool largeIcon)
                      ^
Add-Type: (16,24): error CS0103: The name 'Icon' does not exist in the current context
                return Icon.FromHandle(largeIcon ? large : small);
                       ^
Add-Type: Cannot add type. Compilation errors occurred.

Thanks

NK


Retrieving specific set of data from CSV file

$
0
0

Hi,

As you can see in the screen shot above, there are 2 sets of data, 1 for Windows and 1 for VMware.

What I want to do is to run a script that will only read the Windows Start to Windows End part of the data, and a second script that only read VMware part of the data.

I could not find a way to do this, is it even possible.

Thank You

Appened to adjacent cell in CSV file

$
0
0

HI,

I'm not great with powershell but it's what I know best so I'm trying to use it to do the following:

I need to extract data like below from AD:

$users = (import-csv "$path\users.csv").users
Foreach ($user in $users){

$Dname = Get-ADUser $user -properties TelephoneNumber| select TelephoneNumber
$Email =  Get-ADUser $user -properties UserPrincipalName | select UserPrincipalName
}

and append it to an adjacent cell in an existing csv file(i.e specify the column it writes to and only write on the same row as the matching username in users.csv)

any assistance with this would be appreciated

regards,

Ian

How can I export and import client certificate using PowerShell script without password-error?

$
0
0

<Problem>

 I tried to install client certificate to client computer. But password error was displayed. 

 Procedure that I performed is following.
  1. I exported the pfx file using PowerShell script with the password.(*1)
  2. I copied the pfx file to client computer.
  3. I double-clicked the pfx file of the client computer. (Import-wizard has started).
  4. Select Current User and pushed "NEXT" button.
  5. Pushed "NEXT" button.
  6. Enter password and Pushed "NEXT" button (Then the dialog box with "The password you entered is incorrect." was displayed.

 Is it because that PowerShell's export-pfxCertificate command can not includes Secret key?

 In the case that pfx file is exported by certificate-export-wizard, certificate-import-wizard  is succeeded and my application works fine. Following is detail of the error.

Best regards.

<Detail of Error>

Import-PfxCertificate : The PFX file you are trying to import requires either a different password or membership in an Active Directory principal 

to which it is protected.

At C:\Work\TestService2\test_import.ps1:11 char:1

+ Import-PfxCertificate -Password $secure_pwd -FilePath "${client_cert_ ...

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo : NotSpecified: (:) [Import-PfxCertificate], Win32Exception

    + FullyQualifiedErrorId : System.ComponentModel.Win32Exception,Microsoft.CertificateServices.Commands.ImportPfxCertificate

<C# Source Code>

            cf.Credentials.ClientCertificate.SetCertificate(
                                        StoreLocation.CurrentUser, StoreName.Root,
                                        X509FindType.FindBySubjectName, "FirstClientCert"
                                        );

<Power Shell Script for exporting>*1

$current_directory = 'D:\Work\TestService2'
$root_cert_name = 'FirstRootCert'
$client_cert_name = 'FirstClientCert'
#$imd_sert_name = 'FirstImdCert'
$pwd = 'xxxxxxxx'
$port_no = 5000
$service_guid = '541eea84-c788-4d23-b6b2-f5210xxxx5c5'

#1. Change the current directory.
Set-Location $current_directory

#2. Encrypt the password.
[System.Security.SecureString]$secure_pwd = ConvertTo-SecureString -String $pwd -Force -AsPlainText

#3. Create a root certificate.
$root_cert = New-SelfSignedCertificate -Type Custom -KeySpec Signature -Subject "CN=${root_cert_name}" -KeyExportPolicy Exportable -HashAlgorithm sha256 -KeyLength 2048 -CertStoreLocation "Cert:\CurrentUser\My" -KeyUsageProperty Sign -KeyUsage CertSign

#4. Export personal information exchange file and private key from root certificate.
[String]$rootCertPath = Join-Path -Path 'cert:\CurrentUser\My\' -ChildPath "$($root_cert.Thumbprint)"
Export-PfxCertificate -Cert $rootCertPath -FilePath "${root_cert_name}.pfx" -Password $secure_pwd
Export-Certificate -Cert $rootCertPath -FilePath "${root_cert_name}.crt"

#5. Create a client certificate.
$client_cert = New-SelfSignedCertificate -Type Custom -DnsName $client_cert_name -KeySpec Signature -Subject "CN=${client_cert_name}" -KeyExportPolicy Exportable -HashAlgorithm sha256 -KeyLength 2048 -CertStoreLocation "Cert:\CurrentUser\My" -Signer $root_cert -TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.2")

#6. Export personal information exchange file and private key from client certificate.
[String]$rootCertPath = Join-Path -Path 'cert:\CurrentUser\My\' -ChildPath "$($client_cert.Thumbprint)"
Export-PfxCertificate -Cert $rootCertPath -FilePath "${client_cert_name}.pfx" -Password $secure_pwd
Export-Certificate -Cert $rootCertPath -FilePath "${client_cert_name}.crt"

<Power Shell Script for Importing>*2

$current_directory = 'C:\Work\TestService2'
$client_cert_name = 'FirstClientCert'
$pwd = 'xxxxxxxx'

#1. Change the current directory.
Set-Location $current_directory

#2. Encrypt the password.
[System.Security.SecureString]$secure_pwd = ConvertTo-SecureString -String $pwd -Force -AsPlainText

#3. Import PFX file.
Import-PfxCertificate -Password $secure_pwd -FilePath "${client_cert_name}.pfx" -CertStoreLocation 'Cert:\CurrentUser\My'



Viewing all 21975 articles
Browse latest View live


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