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

Best way to read the Certificate in powershell?

$
0
0

Hi team,

I have a module, which needs a certificate to encrypt:

Till date I am using it as part of the script as $var(the data type is string) . When I pass this to the below logic it's working.

 $Cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
 $Cert.Import([Convert]::FromBase64String($CertBlob))

Now I want to keep the contents of cert to a file(BlobCert.txt) and read it in powershell in runtime as follows:

$data = Get-Content ("$PSScriptRoot\BlobCert.txt"); But here the data type of $data is Object[]/System.array.

$StringData = [System.Text.Encoding]::Unicode.GetBytes($data)
$CertBlob = [System.Convert]::ToBase64String($StringData)

This is throwing an error:

Exception calling "Import" with "1" argument(s): "Cannot find the requested object.
"
At F:\D\PWNPATH\src\ADE\Crawler\ADCrawler\Encrypt.psm1:35 char:4
+             $Cert.Import([Convert]::FromBase64String($CertBlob))
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : CryptographicException

Please let me know how can we solve this or is there a better way to read out the certificates in powershell

PS:

$var = @"
MIIHojCCBYqgAwIBAgITLQAALJZ2eDYUeb1QYQABAAAsljANBgkqhkiG9w0BAQsF
ADCBjzELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNVBAcT
B1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jwb3JhdGlvbjEVMBMGA1UE
CxMMTWljcm9zb2Z0IElUMSIwIAYDVQQDExlNaWNyb3NvZnQgSVQgSVRPIFNTTCBD
QSAxMB4XDTE1MTEwNjIwMzMyM1oXDTE3MTEwNTIwMzMyM1owaDELMAkGA1UEBhMC
VVMxCzAJBgNVBAgTAldhMRAwDgYDVQQHEwdSZWRtb25kMRIwEAYDVQQKEwlNaWNy
b3NvZnQxEDAOBgNVBAsTB1NlcnBlbnQxFDASBgNVBAMT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JJAj4FjmnTxFZ/BfbYZ1/LgcLj39x20lMoS0
WIXL44GJnVFkwVSCY1eaY1mDZKKBbCAo8zfJ+373RM6YLTh4cTM=
"@


Komal.


Script to delete files older than N days but not delete files from X list days

$
0
0

I am looking the way to delete all files older than 45 days in PS but want save files from dates 30 and 31 or the last file of each month.

Scheduled reboot with a message

$
0
0

Hi together,

I'd like to realize following:

1) Restart all member computers in a domain group in a scheduled day / time.

2) Scheduled day / time is on Wednesday each 2 weeks.

3) 15 minutes before the server is rebooted, a user group should get an emailthat the computers will be rebooted in 15 minutes.

4) All applications should be forced to close.

5) In each reboot, a log file of the reboot should be generated and saved in a local folder.

6) The scheduled reboot script will be used with a domain group policy.

I can restart the Computers with following script. But how can I realize others?

Get-ADGroupMember "Domain group to restart" |
    ForEach-Object{
        Restart-Computer -ComputerName $_.Name
    }
 

Best Regards

Birdal





Unable to import ActiveDirectory module on Windows 2012 R2 using Powershell version 2.0

$
0
0

We have a Windows 2012 R2 OS with the default Powershell version 4.0 installed.

PS C:\Users\Administrator> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      4.0
WSManStackVersion              3.0
SerializationVersion           1.1.0.1
CLRVersion                     4.0.30319.34014
BuildVersion                   6.3.9600.16394
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion      2.2

If a launch a Powershell console and run:

Import-Module ActiveDirectory

Everything works fine.

However, we actually call our powershell scripts from a 3rd party app that only supports up to Powershell version 2.0.

The problem is I can't load the ActiveModule when running Powershell version 2.0.

If I start the Powershell console with powershell -Version 2.0 and try to load the ActiveDirectory module, I get the following:

PS C:\Users\Administrator> $PSVersionTable

Name                           Value
----                           -----
CLRVersion                     2.0.50727.8000
BuildVersion                   6.1.7600.16385
PSVersion                      2.0
WSManStackVersion              2.0
PSCompatibleVersions           {1.0, 2.0}
SerializationVersion           1.1.0.1
PSRemotingProtocolVersion      2.1


PS C:\Users\Administrator> Import-Module ActiveDirectory
Import-Module : The 'C:\windows\system32\WindowsPowerShell\v1.0\Modules\ActiveDirectory\ActiveDirectory.psd1' module ca
nnot be imported because its manifest contains one or more members that are not valid. The valid manifest members are (
'ModuleToProcess', 'NestedModules', 'GUID', 'Author', 'CompanyName', 'Copyright', 'ModuleVersion', 'Description', 'Powe
rShellVersion', 'PowerShellHostName', 'PowerShellHostVersion', 'CLRVersion', 'DotNetFrameworkVersion', 'ProcessorArchit
ecture', 'RequiredModules', 'TypesToProcess', 'FormatsToProcess', 'ScriptsToProcess', 'PrivateData', 'RequiredAssemblie
s', 'ModuleList', 'FileList', 'FunctionsToExport', 'VariablesToExport', 'AliasesToExport', 'CmdletsToExport'). Remove t
he members that are not valid ('HelpInfoUri'), then try to import the module again.
At line:1 char:14
+ Import-Module <<<<  ActiveDirectory
    + CategoryInfo          : InvalidData: (C:\windows\syst...eDirectory.psd1:String) [Import-Module], InvalidOperatio
   nException
    + FullyQualifiedErrorId : Modules_InvalidManifestMember,Microsoft.PowerShell.Commands.ImportModuleCommand

Is there any workaround for this issue as I don't have the option of running the Powershell scripts above version 2.0?

Remove ActiveSync Devices in EXO using ForEach statements

$
0
0

I looking to remove <g class="gr_ gr_5 gr-alert gr_spell gr_run_anim gr_inline_cards ContextualSpelling ins-del multiReplace" data-gr-id="5" id="5">activesync</g> devices associated with a user.
I'm having issues with the part 2 "The operation couldn't be performed because xxxxxxxxxxxx matches multiple entries."

#import users
$users = Get-Content -Path "C:\RemoveActiveSync.txt"

#Part 1:Remove allowed and blocked devices
foreach ($user in $users){Set-CASMailbox -Identity $user -ActiveSyncAllowedDeviceIDs:$null; Set-CASMailbox -Identity $user -ActiveSyncblockedDeviceIDs:$null}

#Part 2:Remove the device partnership from the user.
foreach ($user in $users){
$EASDEVICES = Get-MobileDevice -Mailbox $user | select Identity
foreach ($EASDEVICE in $EASDEVICES) {Remove-MobileDevice -Identity $EASDEVICE.identity -Confirm:$false
}
}


Thank You !!!

Uninstalling Software using PowerShell

$
0
0

Right, this is what I have.. I understand why its not working but cant think of way round it or easier way to get to the point I want to be at..

I have script where I can check disk space and install on the local or remote machines.. this works fine.. But I've been advised to follow best practice I should incorporate something that checks where a version is already installed and install it if necessary..

Here's a similar representation of the piece of script  -

$FileName = get-itemproperty 'C:\Powershell\Blah Blah Blah 1.1.1.1 Installer.msi' | Select name
Get-WmiObject -Class Win32_Product | Where-Object {$_.Name -like "$FileName"} | foreach-object -process {$_.Uninstall()}

It doesn't find the software installed to be able to install it.. I've checked..

But when I Type the following -

Get-WmiObject -Class Win32_Product | Where-Object {$_.Name -eq "Blah Blah Blah"} | foreach-object -process {$_.Uninstall()}

Basically the same as the top example without the '1.1.1.1 Installer.msi' part.. It has the expected result - It picks up the installed software and installs correctly..

Is there a way to get round this or an easier way to look to see if the software or previous versions are installed and if there is.. to uninstall them?

A friend of mine mentioned 'Uninstall Stings' but after research they confuse me a bit..

Any guidance or assistance is greatly appreciated..

Thanks Guys - Loving the PowerShell Community :)

How can I rename files and append datetime?

$
0
0
Hi, 
I need rename many files append _datetime (20170124_145010) before their extension and move them to another directory. How can I do it?
I would like to run it within a stored procedure.

Ex:  Source is:
dir c:\source
abc.txt
bcde.txt
cdf.txt
1234_1.txt
bcde_2.txt

Destination is:
dir c:\dest
abc_20170124_145010.txt
bcde_20170124_145010.txt
cdf_20170124_145010.txt
1234_1_20170124_145010.txt
bcde_2_20170124_145010.txt

Tks

Help adding details of power shell output in email

$
0
0

Hi All,

I've stolen some and written some of the script below that should show the before status of the MMA service and restarting the service then showing the status of the service after it was restarted.  I'm going to execute this script twice a week on our SCSM server. 

The part I need most help with is to send an email with the outcome of the script in the body of the email. I'd love for it to show the steps that powershell took with the final outcome. I hope I make sense . Any help would be greatly appreciated. 

$srvName = "Microsoft Monitoring Agent"
$servicePrior = Get-Service $srvName
"$srvName is now " + $servicePrior.status
Restart-Service $srvName
start-sleep -s 60
$serviceAfter = Get-Service $srvName
"$srvName is now " + $serviceAfter.status
Send-MailMessage -to mclayton@******.com -from BC-SCSM@******.com -subject "Microsoft Monitoring Agent Restarted" -body 'get-service "<Add body here>" -SmtpServer smtp.*******.com

Thank you,

Michael Clayton


Help with a script to keep files....

$
0
0

Hey guys - new to PS and need some help.  I have a script to clean up log files in a directory, but I need to refine it slightly. Currently, it deletes files older than 3 days, which is what I want, but I need it setup so that if there are no newer files, it wont delete the latest logs (even if older than 3 days). If no files are written to the directory, then on the 4th day, I have no logs at all, and I'd like to add some logic so that even if more than 3 days old, if its the last file in the directory, dont delete it so that I can retain the last logs, even if older than 3 days.

Here's what I have right now....

$Path = "D:\Test"

$Days = "-3"

$DateNow = Get-Date

$DeleteDate = $DateNow.AddDays($Days)

Get-ChildItem $Path -Recurse | Where-Object {$_.LastWriteTime -lt $DeleteDate } | Remove-Item

Thanks!

File in Use open Read only

$
0
0

$AllMyDocs=Get-ChildItem -Path $oneFolder -Filter * -Recurse | Select Name, FullName | where {($_.Name -like "*.docx") -or ($_.Name -like "*.doc")} ForEach ($myDoc in $AllMyDocs) { $Name=($myDoc.Name) $fullPath=($myDoc.FullName)"{0} {1}" -f $Name, $fullPath $Word = New-Object -ComObject Word.Application $Word.Visible = $false $Document = $Word.Documents.open($fullPath) $Document.tables | ForEach { foreach ($row in $_.rows) { $(foreach ($cell in $row.cells) { #$cell.range.text $cell.range.Paragraphs | %{ $mystring=$_.Range.Text IF([string]::IsNullOrEmpty($mystring)) { } else { Write-Host $mystring $NewObject01 = new-object PSObject $NewObject01 | add-member -membertype NoteProperty -name "Street Name" -Value $mystring $NewObject01 | add-member -membertype NoteProperty -name "Document Name" -Value $fullPath $oArray01 += $NewObject01 $oArray01 | Export-Csv -Path "c:\temp\script\Samuel\HansonStreet.csv" #Read-Host } } } ) } }

When I run the code I get the prompt and stops. How do tell the script to not to prompt and read the file?

PLease help


syntax of repeated conditionals?

$
0
0

Hi Experts, 

I'm new to powershell and wondering why this throws an error :

$all =[long] [Microsoft.SqlServer.Management.Smo.DatabaseObjectTypes]::Table `
        -bor [Microsoft.SqlServer.Management.Smo.DatabaseObjectTypes]::View
        -bor [Microsoft.SqlServer.Management.Smo.DatabaseObjectTypes]::StoredProcedure
        -bor [Microsoft.SqlServer.Management.Smo.DatabaseObjectTypes]::UserDefinedFunction
        -bor [Microsoft.SqlServer.Management.Smo.DatabaseObjectTypes]::Schema

But this does not:

$all =[long] [Microsoft.SqlServer.Management.Smo.DatabaseObjectTypes]::Table `
        -bor [Microsoft.SqlServer.Management.Smo.DatabaseObjectTypes]::View  -bor [Microsoft.SqlServer.Management.Smo.DatabaseObjectTypes]::StoredProcedure -bor [Microsoft.SqlServer.Management.Smo.DatabaseObjectTypes]::UserDefinedFunction -bor [Microsoft.SqlServer.Management.Smo.DatabaseObjectTypes]::Schema

Also, is there an equivalent to this (SQL)?  

where DatabaseObjectTypes in ('Table','View','Stored Procedure', 'UserDefinedFunction','Synonym')

Thanks in advance!  

Windows Update is being shutdown for new portal

$
0
0

There are a number of clear impacts.

Read this article for impacts and the new method (RESTfull API) of accessing bulletins.

https://redmondmag.com/articles/2017/01/13/microsoft-replacing-security-bulletins-portal.aspx

MSRC Portal: https://portal.msrc.microsoft.com/en-us/security-guidance

Code samples:

#Get the Updates as XML
Invoke-RestMethod -Uri 'https://api.msrc.microsoft.com/Updates?api-Version=2016' -ContentType application/xml -Headers @{'Api-Key'='{api key}'}

#Get the Updates as JSON
Invoke-RestMethod -Uri 'https://api.msrc.microsoft.com/Updates?api-Version=2016' -ContentType application/json -Headers @{'Api-Key'='{api key}'}

#Get the CVRF with ID 2016-Nov as XML
Invoke-RestMethod -Uri 'https://api.msrc.microsoft.com/cvrf/2016-Nov?api-Version=2016' -ContentType application/xml -Headers @{'Api-Key'='{api key}'}

#Get the CVRF with ID 2016-Nov as JSON
Invoke-RestMethod -Uri 'https://api.msrc.microsoft.com/cvrf/2016-Nov?api-Version=201'6 -ContentType application/json -Headers @{'Api-Key'='{api key}'}


\_(ツ)_/


Adding printer under System account fails

$
0
0

Added a printer by IP to computer-1.

Than shared it as printer-1, password protected sharing is turned off.

Than from another computer, trying to add it using Add-Printer cmdlet.

Add-Printer -ConnectionName '\\computer-1\printer-1'

When executed under a regular account, the printer is added successfully, when executed under System it fails :

Add-Printer : Access was denied to the specified resource.

How to change home drive server from list

$
0
0

Hi

I have a list of user which I need to change the home drive path - I am starting from this script and I would like to use a foreach command but I can't my head around:

Get-ADUser -filter {homedirectory -like "*domainname*\homefolders*"} -property homedirectory | select Name, Samaccountname, homedirectory 

The home drive is set to DFS path which I am changing back to point to the file server name - so the path on AD Users Account should be: \\FPS01\homefolders\%username% 

How can I make a foreach command to change the path please?

Maelito


Maelito

Format PowerShell Code

$
0
0

Hi All,

I am currently using the PowerShell ISE to write PowerShell scripts at work.

Is there anyway I can format the code to make it more easier to read? In Visual Studio it is easy to format any C# code by pressing an menu button, but I can not find any easy way to format PowerShell code. Is there a website that formats PowerShell code?

I hope you can help

Colin



AppLocker rules (White List) do not work in W7 for PowerShell 5 scrips

$
0
0

In version 5, PowerShell now reduces its functionality to “Constrained Mode” for both interactive input and user-authored scripts when it detects that PowerShell scripts have an ‘Allow Mode’ policy applied to them.

Scripts that are allowed by the AppLocker policy (for example: signed by the enterprise’s trusted code signing certificate, or in a trusted directory) are not subject to Constrained Language. They have access to the extended capabilities of the PowerShell language disallowed by Constrained Language. This includes unverifiable extensions such as .NET scripting, and invocation of Win32 APIs.
Source: https://blogs.msdn.microsoft.com/powershell/2015/06/09/powershell-the-blue-team/

We have identical AppLocker rules, both W7 and W10, in use. Defined AppLocker rules (White List) do not work in W7! In W10 with PowerShell 5, everithing works like described.

Is this a BUG in WMF 5.0 for W7?


Martin Schneeberger

generate normal password for ad users from csv

$
0
0

hey guys , 

im trying to reset ad users from a csv file and i found numerous powershell scripts about it and it works great

but the problem is the generated password are too heave for example 

"6{_@?79v" and " ug+[HiT; " ... 

[CmdletBinding(SupportsShouldProcess=$true,
					ConfirmImpact="High",
					DefaultParameterSetName="OU")]
	param
	(
		[Parameter(Mandatory=$true,Position=0,ParameterSetName="Path")]
		[String]$Path,
		[Parameter(Mandatory=$True,Position=0,ParameterSetName="OU")]
		[String[]]$OrganizationalUnit,
		[Parameter(Mandatory=$false,Position=1,ParameterSetName="OU")]
		[String]$Password,
		[Parameter(Mandatory=$false,Position=2,ParameterSetName="OU")]
		[switch]$Recurse,
		[Parameter(Mandatory=$false,Position=3)]
		[String]$CSVPath="C:\Result$(Get-Date -Format "MMddyyyy").csv"
	)
	process
	{
		Add-Type -Assembly System.Web
		$result=@()
		$OUList=@()
		$UserList=@()
		if ($Pscmdlet.ParameterSetName -eq "Path")
		{
			if (Test-Path $Path)
			{
				$UserList=Import-Csv $path
				$ProgressTitle="Reset password for users specified in $path"
			}
			else
			{
				$errorMsg="Could not find '$path'. Please make sure the path is correct."
				Write-Error -Message $errorMsg
				return
			}
		}
		else
		{
			foreach ($OU in $OrganizationalUnit)
			{
				$OUList+=Get-ADOrganizationalUnit -Filter 'name -like $OU'
			}
			$OUList|select Name,DistinguishedName
			if ($Recurse)
			{
				$SearchScope="Subtree"
				Write-Host "Users' passwords, in these OUs and their sub-ous, will be reset."
				$DNList+=$OUList|ForEach-Object {$_.distinguishedname}
				#Remove duplicate child OU , if exists.
				foreach ($TempOU in $OUList)
				{
					foreach ($DN in $DNList)
					{
						if ($TempOU.DistinguishedName -like "*?$DN")
						{
							$OUList= $OUList -notmatch $TempOU
							#write-verbose
							$verboseMsg = "Duplicate OU:$TempOU is a child OU of $DN."
							Write-Verbose -Message $verboseMsg
							break
						}
					}
				}
			}
			else
			{
				$SearchScope="Onelevel"
				Write-Host "Users' passwords, in these OUs above, will be reset."
			}
			foreach ($TempOU in $OUList)
			{
				$UserList+=Get-Aduser -Filter 'enabled -eq $true' -ResultSetSize $null -SearchBase $TempOU -SearchScope $SearchScope -Properties samaccountname
			}
			$ProgressTitle="Reset password for users in given OUs"
		}
		if($PSCmdlet.ShouldProcess("these users"))
		{
			foreach ($user in $UserList)
			{
				$Identity=$user.SamAccountName
				if ([System.String]::IsNullOrEmpty($Password))
				{
					if ([System.String]::IsNullOrEmpty($user.Password))
					{
						#generate a password with 10 character
						$NewPassword=[Web.Security.Membership]::GeneratePassword(10,3)
					}
					else
					{
						$NewPassword=$user.Password
					}
				}
				else
				{
					$NewPassword=$Password
				}
				#write progress
				$Counter++
				Write-Progress -Activity $ProgressTitle -Status "Processing" -CurrentOperation $Identity -PercentComplete ($counter / ($Userlist.Count) * 100)
				#reset password
				Set-AdaccountPassword -Identity $Identity -Reset -NewPassword (ConvertTo-SecureString -AsPlainText $NewPassword -Force)
				#export a csv file
				$Account = New-Object PSObject
				$Account | Add-Member -MemberType NoteProperty -Name "Identity" -Value $Identity
				$Account | Add-Member -MemberType NoteProperty -Name "NewPassword" -Value $NewPassword
				$result+=$Account
			}
			$result|Export-Csv -Path $CSVPath -NoTypeInformation -Force
		}
	}
}

i got this one from technet ... how can i make it generate just normal passwords alphanumeric just lowercase letters and numbers ?


RM


Newbie looking at creating a script to add users groups based on mailbox DB.

$
0
0

Hi,

I've only ever used basic PS admin commands for exporting or importing basic info on AD/Exchange.

I'm looking to create a script which does the following:

  • Gets users from a particular AD group (I can do this bit using Get-ADGroupMember)
  • For each of these users I want to find out which mailbox database they are located on (Get-Mailbox)?
  • Then I want to somehow create AD groups DatabaseA, DatabaseB, DatabaseC etc. and add the users to these groups based on which DB they reside on.

The idea is then to schedule this to run every day to update them.

Can anyone help me out?

Thanks

Search_AD_Local_Admin_Email.ps1 is not working

$
0
0

Hi everyone,

The following script is not working with PowerShell 2.0 or 4.0 (Win2008R2 or Win2012R2), can someone help me out? Thanks.

https://gallery.technet.microsoft.com/scriptcenter/Search-AD-Collect-Local-9952be71

the error what I got is below:

Search_AD : The term 'Search_AD' 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 D:\Scripts\Get-LocalGroupAllMembers\Search_AD_Local_Admin_Email.ps1:13
char:1
+ Search_AD
+ ~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Search_AD:String) [], CommandNo
   tFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Search_LAdmin : The term 'Search_LAdmin' 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 D:\Scripts\Get-LocalGroupAllMembers\Search_AD_Local_Admin_Email.ps1:14
char:1
+ Search_LAdmin
+ ~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Search_LAdmin:String) [], Comma
   ndNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Send_Email : The term 'Send_Email' 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 D:\Scripts\Get-LocalGroupAllMembers\Search_AD_Local_Admin_Email.ps1:15
char:1
+ Send_Email
+ ~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Send_Email:String) [], CommandN
   otFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

How to add my script to one variable

$
0
0

Hello,

I have a script that I need to be put in to a variable so I can have the script output emailed. Is there a way to do that wit this script?

$srvName = "Adobe Acrobat Update Service"
$servicePrior = Get-Service $srvName
"$srvName is now " + $servicePrior.status
Stop-Service $srvName
start-sleep -s 120
Start-Service $srvName
start-sleep -s 120
$serviceAfter = Get-Service $srvName
"$srvName is now " + $serviceAfter.status

Viewing all 21975 articles
Browse latest View live


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