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

Windows File Share Export

$
0
0

Hi,

Looking for powershell script to export All file shares in the fileserver including subfolders with permission, Owner, creation date, last access date into a csv file.

Using Windows 2008 r2 as file server.


Sathya Paul


Powershell with WSS Username Token profile 1.0

$
0
0

Hello. Been trying to authenticate with a web service using powershell. Using Invoke-WebServiceProxy (with -credential), I am able to obtain the list of available methods. However when trying to invoke I receive a authentication error response. Further reading reveal this particular web service employs the WSS Token Profile 1.0 standard with Password Digest.

For some reason any credentials passed don't appear to be accepted (tested valid credentials through SOAP UI, where successfully received data). Is there any way I could add the required authentication headers to my request, or even better if powershell is able to employ the WSS Token Profile 1.0 standard. Any help is appreciated

Powershell and SQL

$
0
0

Hi,

I'm a newbie to PowerShell and need a helping hand on how to even get started with it!

We have the SQLPS and SQLASCMDLETS modules installed which we want to use to query some information in a table.

The SQL query is as follows:

select Hostname as Hostname, count(*) as NoOfActivities

from LoggedOnUserActivity

where Hostname in ('Server1','Server2','Server3')

and LastActivityTime > DATEADD(HH,-2,GETDATE())

group by Hostname

If the LastActivityTime is more than two hours ago, there would be no results displayed, so in this case we would want to restart the service of that particular service through powershell. If there are results returned, then we do not want powershell to restart the service.

Hope this explains to you what I'm looking for as an end result.

Thanks,
Daniel

Powershell & Updating SQL table - Exception Error

$
0
0

Hello!

I am trying to use powershell to update a SQL database table.

Here is a screenshot of the script i am trying to use within ISE:

I am basically just trying to update the USERS (stores door codes) with a new first and last name. Any ideas what i might be doing wrong here?

I am able to query the USERS table fine with this script:

Thank you in advance!

Pass command arguments within a Start-Process string help

$
0
0

I am trying to run a process using a variable defined in the script.

The variable in this case is $compname.

What I have is this:

            Start-Process isscntr /a$compname /c"Remote Control"
            Pause 
            CheckHost

isscnter requires the quotes in the /c"Remote Control" as part of the command switch.

Obviously Powershell barks about the quotation marks in the switch.

Is there a way to pass the switch through as needed so isscntr can use it?

Thanks, Dan L


Read Content From File

$
0
0

I have a txt File named changeletter.txt with the following line on it

C:\Program Files\

I'm trying to read the content of the file to check for the existence C:\ in the following statement:

If ((Get-Content -Path "C:\changeletter.txt").Contains("C:\") -eq $true){

   Do something here

}

However, it seems to be ignoring the existence of C:\ on the file because it's written as C:\Program Files\

If I remove C:\Program Files\ from the text file and only have C:\ then the value returns true and enters the If Statement.

What I'm I missing?

Missing ManagedComputer Class after enabling AlwaysOn support for SQL server

$
0
0

Hello,

I'm developing a script for installing our SQL servers. Currently I have an issue with enabling AlwaysOn and restarting the SQL Server services.

 

$env:PSModulePath=[Environment]::GetEnvironmentVariable("PSModulePath", "Machine")
Import-Module sqlps
Set-Location C:\WINDOWS\system32

#Enable-SqlAlwaysOn -Path SQLSERVER:\SQL\SV1400167\INST1 -NoServiceRestart

Set-Location SQLSERVER:\SQL\SV1400167 #Switch to SQL Server
(get-item .) | select *
Set-Location C:\WINDOWS\system32

 

I get the result (The option ManagedComputer has a value):

 

DisplayName     :
PSPath          : Microsoft.SqlServer.Management.PSProvider\SqlServer::SQLSERVER:\SQL\SV1400167
PSParentPath    : Microsoft.SqlServer.Management.PSProvider\SqlServer::SQLSERVER:\SQL
PSChildName     : SV1400167
PSDrive         : SQLSERVER
PSProvider      : Microsoft.SqlServer.Management.PSProvider\SqlServer
PSIsContainer   : False
MachineName     : SV1400167
ManagedComputer : Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer
Servers         : {[INST1, Microsoft.SqlServer.Management.PowerShell.Extensions.ServerInformation]}

 

When I enable the line "#Enable-SqlAlwaysOn -Path SQLSERVER:\SQL\SV1400167\INST1 -NoServiceRestart", this option is suddenly empty

 

$env:PSModulePath=[Environment]::GetEnvironmentVariable("PSModulePath", "Machine")
Import-Module sqlps
Set-Location C:\WINDOWS\system32

Enable-SqlAlwaysOn -Path SQLSERVER:\SQL\SV1400167\INST1 -NoServiceRestart

Set-Location SQLSERVER:\SQL\SV1400167 #Switch to SQL Server
(get-item .) | select *
Set-Location C:\WINDOWS\system32

 

DisplayName     :
PSPath          : Microsoft.SqlServer.Management.PSProvider\SqlServer::SQLSERVER:\SQL\SV1400167
PSParentPath    : Microsoft.SqlServer.Management.PSProvider\SqlServer::SQLSERVER:\SQL
PSChildName     : SV1400167
PSDrive         : SQLSERVER
PSProvider      : Microsoft.SqlServer.Management.PSProvider\SqlServer
PSIsContainer   : False
MachineName     : SV1400167
ManagedComputer :
Servers         : {[INST1, Microsoft.SqlServer.Management.PowerShell.Extensions.ServerInformation]}

 

Does anyone know how I can get this class back again? It is only related to the session in which I'm active, If I start another session, the class is available. I have tried to remove the module sqlps after "Enable-SqlAlwaysOn " and import it again, but that didn't work.

 

Regards,
Marco




Collect Registry Data on Remote Machine, without invoke-command and with credentials?

$
0
0

Hi,

So I'm struggling to find a way to collect all of the registry entries in "SOFTWARE\Microsoft\Windows NT\CurrentVersion" on a remote machine, that I can pass login credentials to. I'm looking to replicate what Win32_Product does initially, but will also want to grab other info from the registry too. I've read that Win32_Product isn't a good idea to run as it can cause issues, its also slow as hell. So I'm trying to figure out an alternative.

I'm trying to convert a VBS script over into Powershell, got everything working. But this.

The Get-WmiObject seems like the way to do it, but I can't figure out how to get it to grab multiple entries like Win32_Product does.

$reg = Get-WmiObject -List -Namespace root\default -ComputerName $Computer -Credential $Cred | Where-Object {$_.Name -eq "StdRegProv"}
$HKLM = 2147483650
$reg.GetStringValue($HKLM,"SOFTWARE\Microsoft\Windows NT\CurrentVersion","ProductName").sValue

This will grab a single value, but I can't figure out how to modify it so that I can get all values.

My attempt at modifying it with the below doesn't work. :(

$reg = Get-WmiObject -List -Namespace root\default -ComputerName $Computer -Credential $Cred | Where-Object {$_.Name -eq "StdRegProv"}
$HKLM = 2147483650

$RegKey = $reg.EnumValues($HKLM,$KeyAddress)

$SubKeys = $RegKey.GetSubKeyNames()

Foreach($key in $SubKeys) {
    $thiskey = $UninstallKey+"\\"+$Key
    $ThisSubKey = $Reg.OpenSubKey($ThisKey)
    $DisplayName = $ThisSubKey.GetValue("DisplayName")
    Write-Host $ComputerName, $DisplayName
}


...

Using .Net works, kind of - But ...

1) I can't work out how to pass credentials

2) The below code will only pull the root folders of HKEY_LOCAL_MACHINE. The OpenSubKey isn't doing what I'd expect.

3) I'll need to modify it so that it actually writes results to an object/array.

$key = "SOFTWARE\Microsoft\Windows\CurrentVersion"
$type = [Microsoft.Win32.RegistryHive]::LocalMachine
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($type, $Computer)
$regKey = $regKey.OpenSubKey($key)
Write-Host "Sub Keys"
Write-Host "--------"
Foreach($sub in $regKey.GetSubKeyNames()){$sub}
Write-Host
Write-Host "Values"
Write-Host "------"
Foreach($val in $regKey.GetValueNames()){$val}

I feel like I've checked every link online about this to no avail.

If only Get-ItemProperty had a -MachineName -Credentials properties! It's so tidy, simple and fast... :(

Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | select DisplayName, Publisher, InstallDate

Just as a further note, this codes going into RunSpaces to be performed in parallel. But I can't guarantee that Invoke-Command will be enabled on the target computer. I'm also trying to target the script to run in Powershell 2.0 if possible.

Thanks for any help or links that will point me in the right direction.



adding custom x-headers to e-mails using the send-mailmessage powershell

$
0
0

Hi,

I am sending e-mails through Win 2012 task scheduler using PowerShell send-mailmessage command, I would like to add a custom x-header to these e-mails, how can I do this? Thanks

How to export specific services to excel and mark color as red if not running if running i want mark it as Green color

$
0
0

Hi Team,

I am performing some health checks on few servers to check the services status.some on please help the code

on How to export specific services to excel and mark color as red if not running if running i want mark it as Green color

I know the code to export but not know how to change the color if stopped

please advice..


Get-VMSnapshot Doesn't work in Enter-PSsession script

$
0
0

Hello,

I have encountered the issue writing this small script.

For some reason it works if I run it line by line, but if I run the whole script it fails.

This is the error I get:

Get-VMSnapshot : The term 'Get-VMSnapshot' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:3 char:30
+ Invoke-Command -ScriptBlock {Get-VMSnapshot –VMName "PC000006_UAT" -Name "PC0000 ...
+                              ~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Get-VMSnapshot:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

And this is the script:

Enter-PSSession -ComputerName "$Machine_name"

Invoke-Command -ScriptBlock

{Get-VMSnapshot –VMName "PC000006_UAT" -Name "PC000006_UAT Backup"  Sort-Object CreationTime -Descending |

Select-Object -First 1 |

Restore-VMSnapshot -Confirm:$false -ErrorAction Stop }

Exit-PSSession

Thank you for your help



Move Folders listed in CSV file

$
0
0

Hello,

I'm currently migrating home folders from one server to another.  During the process I thought it would be a good idea to clean up some of the stale home directories.  The accounts have been disabled/deleted in AD when people leave but the H: drives were never deleted.  All of the home directories have been restored to a folder on the new server.  I would like to use powershell to copy the folders with names listed in a CSV file to a new directory, leaving only the folders that are not listed on the csv file.

Any assistance will be greatly appreciated. 


Loaded .Net Assembly, but cannot find type

$
0
0

I'm trying to create some automation around Adobe's API to create Adobe Federated IDs for our users. This requires creating a signed JSON web token. The assemblies I am working with are System.IdentityModel.Tokens.Jwt.dll (which I downloaded using Nuget.exe) and Microsoft.IdentityModel.Tokens.dll which System.IdentityModel.Tokens.Jwt.dll depends on. I'm Running Windows 10 / Powershell 5 and have the Windows Identity Foundation feature installed.

The question is why do I run into "New-Object : Cannot find type [System.IdentityModel.Tokens.JwtSecurityToken]: verify that the assembly containing this type is loaded." even though the required assemblies appear to be loaded.

Add-Type -Path "C:\Users\andrew\System.IdentityModel.Tokens.Jwt.dll"
[appdomain]::CurrentDomain.GetAssemblies()

Returns:

GAC    Version        Location                                                                                                      
---    -------        --------         
False  v4.0.30319     C:\Users\andrew\System.IdentityModel.Tokens.Jwt.dll                                                                                  
True   v4.0.30319     C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\Microsoft.IdentityModel.Tokens\v4.0_5.0.0.127__31bf3856ad364e35\Microsoft.IdentityModel.Tokens.dll 
True   v4.0.30319     C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.IdentityModel\v4.0_4.0.0.0__b77a5c561934e089\System.IdentityModel.dll                   
(and all other loaded assemblies)

So, it appears the assemblies are loaded. However, when I try to create JSON web token, for example:

$token = New-Object System.IdentityModel.Tokens.JwtSecurityToken($issuer, $audience, $claims, $lifetime, $signingCredentials)  

I get:

New-Object : Cannot find type [System.IdentityModel.Tokens.JwtSecurityToken]: verify that the assembly containing this type is loaded.
At C:\Users\andrew\Desktop\Test.ps1:25 char:14
+ ...    $token = New-Object System.IdentityModel.Tokens.JwtSecurityToken($ ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidType: (:) [New-Object], PSArgumentException
    + FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand
 
So it appears I am missing something... I am looking to just get the System.IdentityModel.Tokens.Jwt.dll assembly loaded so I can begin experimenting with actually making the JWT and working with the Adobe REST APIs.

The example code I am starting with is here: blog.d-apps.com/2013/08/powershell-and-json-web-token-handler.html I am able to successfully create new object from other external assemblies. For example New-Object System.IdentityModel.Protocols.WSTrust.Lifetime etc. works fine.

Thanks in advance for any suggestions I could use to troubleshoot.

Why can't PowerShell find my certificate?

$
0
0

I have been running the following code for two days now and it worked just fine:

if ((Test-Path cert:\CurrentUser\MY\$myCert.Thumbprint) -eq $true){
 $certificate = (Get-Item cert:\CurrentUser\MY\$myCert.Thumbprint)
} else {
 $certificate = (Get-Item cert:\LocalMachine\MY\$myCert.Thumbprint)
}

I have confirmed that the cert with the thumbprint is still installed in the CurrentUser\Personal\Certificates area, and I've confirmed that when I load the certificate (the $myCert varialbe) that the thumbprint is in there, but just today this line of code stopped finding the certificate thumbprint.

I've rebooted and cleared out just about everything I can think of. Not that it matters because everybody has their issues, but this is somewhat urgent. I'm hoping this is just something stupid since it was working earlier and no PS above it was modified in any way.

Any ideas?


STom

How to create a blank new line in an array by comparing lines

$
0
0

I have a script which outputs a list of hosts within a vCenter and details the cluster that each host is in, what I can't figure out is how to insert a blank line into the array whenever the "Cluster Name" of each host changes.

To say it a different way, I want to separate items in a list out by using blank lines, and I want to insert one of these blank lines every time the "Cluster Name" property of each item changes.

                                     

For example at the moment my output is something roughly like this:

Host             Cluster

Host1           Cluster1

Host2           Cluster1

Host3           Cluster2

Host4           Cluster2

               

But I want it to appear like:

Host             Cluster

Host1           Cluster1

Host2           Cluster1

                               

Host3           Cluster2

Host4           Cluster2






Powershell - How to create a blank new line in an array by comparing lines

$
0
0

I have a script which outputs a list of hosts within a vCenter and details the cluster that each host is in, what I can't figure out is how to insert a blank line into the array whenever the "Cluster Name" of each host changes.

To say it a different way, I want to separate items in a list out by using blank lines, and I want to insert one of these blank lines every time the "Cluster Name" property of each item changes.

                                     

For example at the moment my output is something roughly like this:

Host             Cluster

Host1           Cluster1

Host2           Cluster1

Host3           Cluster2

Host4           Cluster2

               

But I want it to appear like:

Host             Cluster

Host1           Cluster1

Host2           Cluster1

                               

Host3           Cluster2

Host4           Cluster2






Convert txt file to csv file with header

$
0
0
I have a txt file with below format. I want to convert this file as a csv file also i need to update header in csv file
for eg:- Employee ID|Legacy ID|Cost Center|User Account
btw first line is blank on this txt file

00005|||Assembler Trainee|user1
00006|||Assembler Trainee|User2
00007|||Assembler Trainee|User3


End result should be like this

Employee ID|Legacy ID|Cost Center|User Account
00005|||Assembler Trainee|user1
00006|||Assembler Trainee|user2
00007|||Assembler Trainee|user3

Regards, Nidhin.CK

Powershell WASP Web Scipt Freezes when ShowDialog() Window Opens - Does not execute further script

$
0
0

Good day,

I am using Powershell with WASP commands to login to Website click on upload, the code works and i click upload to select file the script freezes on ShowDialog winodw to select file

$ie.Document.getElementByID("form:filesField:files:file").Click()  #Upload Button and Dialog PopsUp
Select-Window -Class 'Modal' | Set-WindowActive | Send-Keys 'C:\Temp\20161215.csv~'

The script does not get to the second line of code as its unable to set focus but when i run the second line in another powershell_ise window while dialog is open then it sets focus and works so i tried running another powershell_ise Before or After i click the ShowDialog before it freezes.

Invoke-Expression "C:\Temp\test.ps1"

File test.ps1:

Start-Sleep -Seconds 15
Import-Module WASP -Force
Add-PSSnapin WASP
Select-Window -Class 'Modal' | Set-WindowActive | Send-Keys 'C:\Temp\20161215.csv~'

But before or after does not work or execute as its still freezes, Any help please

Regards



Powershell Web Scipt Freezes when ShowDialog() Window Opens - Does not execute further script

$
0
0

Good day,

I am using Powershell with WASP commands to login to Website click on upload, the code works and i click upload to select file the script freezes on ShowDialog winodw to select file

$ie.Document.getElementByID("form:filesField:files:file").Click()  #Upload Button and Dialog PopsUp
Select-Window -Class 'Modal' | Set-WindowActive | Send-Keys 'C:\Temp\20161215.csv~'

The script does not get to the second line of code as its unable to set focus but when i run the second line in another powershell_ise window while dialog is open then it sets focus and works so i tried running another powershell_ise Before or After i click the ShowDialog before it freezes.

Invoke-Expression "C:\Temp\test.ps1"

File test.ps1:

Start-Sleep -Seconds 15
Import-Module WASP -Force
Add-PSSnapin WASP
Select-Window -Class 'Modal' | Set-WindowActive | Send-Keys 'C:\Temp\20161215.csv~'

But before or after does not work or execute as its still freezes, Any help please

Regards




Capture Winrm issues and wait time while remoting

$
0
0

Need guidance on how to capture Winrm issues during remoting. 

My code is able to capture if the server is offline , however I am not sure how to capture (1) if the server is online but has winrm issues due to which the code would not execute.(2) At times if a server has some issue and is not responding, the script waits eternally until it is manually interupted. Is there some way to add a wait time or would a try , catch block be able to help here but I am personally not convinced (of try catch since the code is working) 

High level / outline view of my code 

$Serverlist = @('server1','server2')

foreach($server in $serverlist)

if(test-connection -computername $server -quiet) {

{

invoke-command -computername $server -scriptblock $dosomething

}

} else { 

# write to file 

}


AK

Viewing all 21975 articles
Browse latest View live


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