For example:
When I use System.Windows.Forms.Form, there is the event "OnClosing". So, when I close a form, some code can be executed.
Can I do something like this, when I stop my powershell script when it is running?
For example:
When I use System.Windows.Forms.Form, there is the event "OnClosing". So, when I close a form, some code can be executed.
Can I do something like this, when I stop my powershell script when it is running?
Hi All, Please may i have your help with translating code from c# to powershell. The code in question uses the openxml sdk and reads an excel file which has both numeric and string data types in the cells.
The C# example code is as follows with the powershell script below. The issue I have is in Powershell I cannot see some of the methods. For example ElementAt or FirstOtDefault. I've highlighted below with ???????? where I'm expecting to see ElementAt. I think the issue is how I'm using generics with constraints in powershell, I might be wrong? Any help would be greatly appreciated
// Retrieve the value of a cell, given a file name, sheet name, // and address name.publicstaticstringGetCellValue(string fileName,string sheetName,string addressName){string value =null;// Open the spreadsheet document for read-only access.using(SpreadsheetDocument document =SpreadsheetDocument.Open(fileName,false)){// Retrieve a reference to the workbook part.WorkbookPart wbPart = document.WorkbookPart;// Find the sheet with the supplied name, and then use that // Sheet object to retrieve a reference to the first worksheet.Sheet theSheet = wbPart.Workbook.Descendants<Sheet>().Where(s => s.Name== sheetName).FirstOrDefault();// Throw an exception if there is no sheet.if(theSheet ==null){thrownewArgumentException("sheetName");}// Retrieve a reference to the worksheet part.WorksheetPart wsPart =(WorksheetPart)(wbPart.GetPartById(theSheet.Id));// Use its Worksheet property to get a reference to the cell // whose address matches the address you supplied.Cell theCell = wsPart.Worksheet.Descendants<Cell>().Where(c => c.CellReference== addressName).FirstOrDefault();// If the cell does not exist, return an empty string.if(theCell !=null){ value = theCell.InnerText;// If the cell represents an integer number, you are done. // For dates, this code returns the serialized value that // represents the date. The code handles strings and // Booleans individually. For shared strings, the code // looks up the corresponding value in the shared string // table. For Booleans, the code converts the value into // the words TRUE or FALSE.if(theCell.DataType!=null){switch(theCell.DataType.Value){caseCellValues.SharedString:// For shared strings, look up the value in the// shared strings table.var stringTable = wbPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();// If the shared string table is missing, something // is wrong. Return the index that is in// the cell. Otherwise, look up the correct text in // the table.if(stringTable !=null){ value = stringTable.SharedStringTable.ElementAt(int.Parse(value)).InnerText;}break;caseCellValues.Boolean:switch(value){case"0": value ="FALSE";break;default: value ="TRUE";break;}break;}}}}return value;}
With my attempt powershell code (not exactly the same) as follows
clsHi,
With the following Get-WmiObject code I can deduce from the “explorer.exe” process, the Domain and User. How can I accomplish the same thing with CIMinstance. (I am in the process of switching to Powershell Core 7.0)
$loggedInfo = Get-WmiObject -Class win32_process -ComputerName $_ -ErrorAction SilentlyContinue | Where-Object{ $_.Name -eq "explorer.exe" } | Select-Object -First 1 |ForEach- object { "logged on " + ($_.GetOwner()).Domain + " \ " + ($_.GetOwner()).User }
Thanks
Mario
I'm trying to create a script which will parse an URL for a specific exe download link and download it. I'm doing this because the download link changes frequently. Below the code:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $path = "https://www.broadcom.com/support/security-center/definitions/download/detail?gid=sep14" $definitionPath = (Invoke-WebRequest $path).Links | Where-Object{$_.InnerText -like "*core15sdsv5i64.exe" -and $_.InnerText -notlike "*.jdb"} | Select-Object -ExpandProperty href $Output = "C:\temp\virus_definition.exe" $start_time = Get-Date Invoke-WebRequest -Uri $definitionPath -OutFile $OutputI receive one error telling me that the argument "$definitionPath" is empty or null. Any ideas how can i fix that?
Thanks.
Hi!
How can I add my C# classes into powershell?
I`ve got 2 classes in different files:
file "check_ciphertext.cs":
using System; namespace tester { public class CipherText_Validator { public CipherText_Validator() { return; } public static string Validate_CipherText(System.String input) { switch ((input.Length == 0) && (input.Length%32 == 0)) { case false: { throw new tester.InvalidCipherTextException(input); } break; default: { return input; } break; } } } }
File "exceptions.cs":
using System; namespace tester{ [Serializable] public class InvalidCipherTextException : System.Exception { public InvalidCipherTextException(System.String ciphertext) : base(System.String.Format("Invalid ciphertext!")) { } } }
File "Main.ps1":
Add-Type -TypeDefinition ([System.Text.Encoding]::ASCII.getString([System.IO.File]::ReadAllBytes(".\classes\c-sharp\exceptions.cs"))) -ReferencedAssemblies "System" Add-Type -TypeDefinition ([System.Text.Encoding]::ASCII.getString([System.IO.File]::ReadAllBytes(".\classes\c-sharp\check_ciphertext.cs"))) -ReferencedAssemblies "System"
When I run Main.ps1, I get exception, that I need to use namespace tester. How can I fix this ?
Hi Everyone,
I wrote a script that automatically adds users who are in one group in AD to another group. The user enters the source group name and the target group name, and the users are then copied automatically.
What I'm missing right now is creating a LOG file at the end of the process that will show which users were added and which failed for some reason - for example, failed to exist in AD.
I would love for ideas. The script looks like this:
$SrcGrp=Read-host-prompt"What is the Source group name?"
$DstGrp=Read-host-prompt"What is the Target group name?"
Add-ADGroupMember-Identity$DstGrp-Members (Get-ADGroupMember-Identity $SrcGrp-Recursive)
this is another script which do the same:
$SrcGrp=Read-host-prompt"What is the Source group name?"
$DstGrp=Read-host-prompt"What is the Target group name?"
Get-ADGroupMember-Identity$SrcGrp|ForEach-Object {Add-ADGroupMember-Identity$DstGrp-Members$_.distinguishedName}
Dear all,
I am implementing a script for AD unlock to automate and improve my colleagues work time.
I have the following scenario:
I have the script hosted at my computer, working with AD module.
Other colleagues will access my computer through PSSession to execute it.
However, they cannot import or use the AD Module cmdlets.
"error initializing default drive: 'unable to contact the server. this may be because this server does not exist, it is currently down, or it does not have the active directory web services running"
Attempt to create the AD PSDrive through AD server running ADWS without success, the following error occurs: "unable to contact the server. this may be because this server does not exist, it is currently down, or it does not have the active directory web services running"
Can you please help me with my implementation or give me an alternative approach?
I've seen a lot pf posts from people whose scripts run fine in ISE but not in a Powershell session. I've got the exact opposite problem - scripts run just fine in Powershell, but don't in ISE. For a specific example, I have a script that presents a list of available PS scripts, then requests the user to select one to run. No matter which one is selected, ISE ignores the choice and simply offers to run the default script. If I run the same script in Powershell (specifying Version 2 when starting 'powershell.exe), the script runs the way it should. It accepts the user input, then runs the corresponding script that was selected.
The server is running Windows 2016.
If it helps:
$ScriptName = $MyInvocation.Mycommand.name ;
$smtpServer = "mymailserver" ;
$Question = " Okay to continue?" ;
$Title = " Verify Continue ..." ;
function Prompt4OK {
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") ;
$Pick = [System.Windows.Forms.MessageBox]::Show($Question , $Title , 4) ;
return $Pick } ;
function Prompt4Answer {
$Answer = $null ;
$Answer = Read-Host 'Okay to Continue - Answer Y or N' ;
return $Answer
} ;
function Prompt4Option {
$FileName = "C:\PS\Master.txt"
Get-ChildItem C:\PS\ | Where-Object {$_.Extension -eq ".PS1"} | `
Select-Object BaseName | Format-Table -HideTableHeaders | out-file $FileName -Force ;
#
$Pick = "NONE" ;
$Option = $null ;
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
#
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "Select a PowerShell Script"
$objForm.Size = New-Object System.Drawing.Size(250,400)
$objForm.Topmost = $True
$objForm.StartPosition = "CenterScreen"
#
$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter")
{$x=$objListBox.SelectedItem;$objForm.Close()}})
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape")
{$objForm.Close()}})
#
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(25,320)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.Add_Click({$Pick=$objListBox.SelectedItem;$objForm.Close()})
$objForm.Controls.Add($OKButton)
#
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(100,320)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.Add_Click({$Pick="CANCEL";$objForm.Close()})
$objForm.Controls.Add($CancelButton)
#
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,20)
$objLabel.Size = New-Object System.Drawing.Size(280,20)
$objLabel.Text = "Please select a PowerShell Script:"
$objForm.Controls.Add($objLabel)
#
$objListBox = New-Object System.Windows.Forms.ListBox
$objListBox.Location = New-Object System.Drawing.Size(10,40)
$objListBox.Size = New-Object System.Drawing.Size(180,120)
$objListBox.Height = 250
#
$Option = Get-Content $FileName ;
foreach ($line in $Option){
$Line = $Line.Trim() ;
IF ($Line.Length -gt 1) { [void] $objListBox.Items.Add("$line" )} ;
} ;
$objForm.Controls.Add($objListBox)
$objForm.Topmost = $True
$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()
#
IF ($Pick.length -lt 2) { $Pick = "NONE" }
# Write-Output "* You Picked: $Pick " ;
IF ($Pick -eq "NONE") {$Powershell = "ListPowershellScripts" } ELSE {$Powershell = $Pick.Trim() } ;
return $Powershell } ;
Clear-Host
Write-Output "* BEGIN * * * * * * * * * * * * * * * * * * $ScriptName * " ;
Write-Output "* " ;
Write-Output "* Please select the Powershell Script to Run. " ;
Start-Sleep -s 1 ;
Write-Output "* " ;
$Powershell = Prompt4Option ;
IF ($Powershell -eq "CANCEL") {Write-Output "* $Powershell * * * * * * * * * * * * * * * * * * $ScriptName *" ; Break} ;
Clear-Host
Write-Output "* BEGIN * * * * * * * * * * * * * * * * * * $ScriptName * " ;
Write-Output "* " ;
$PS1Filename = "C:\PS\" + $Powershell + ".PS1" ;
$PS1FileInfo = "C:\PS\" + $Powershell + ".TXT" ;
Write-Output "* Powershell Script: $Powershell" ;
$PS1Num = $PS1File.Length ;
Write-Output "* " ;
Write-Output "* Powershell Length: $PS1Num" ;
Write-Output "* " ;
Write-Output "* * * * * * * * * * * * * * * * * * Powershell $Powershell Info * * * * * * * " ;
# Write-Output "* " ;
$PS1File = Get-Content $PS1Filename ;
Get-Content $PS1Filename -totalcount 10 ;
Write-Output "* # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # " ;
# Write-Output "* * * * * * * * * * * * * * * * * * Powershell $Powershell Info * * * * * * * " ;
Write-Output "* "
Write-Output "* Do you want to Run the Powershell Script: $Powershell ? ";
Write-Output "* "
$Question = " Okay to Run Powershell Script: $Powershell ?" ;
$Answer = Prompt4OK ;
IF ($Answer -eq "Yes") {
Write-Output "* " ;
Write-Output "* Will Run the Script in a few moments... "
$env:PSMASTERCALLED = $Powershell + ".ps1" ;
Start-Sleep -s 2 ;
$PSScript = $PS1Filename ;
Invoke-Expression $PSScript ; }
ELSE { Write-Output "* No Powershell Script will run" -Foregroundcolor Red } ;
Write-Output "* " ;
Write-Output "* All Done "
Write-Output "* "
Write-Output "* * END * * * * * * * * * * * * * * * * * * $ScriptName * " ;
Dear all,
I am implementing a script for AD unlock to automate and improve my colleagues work time.
I have the following scenario:
I have the script hosted at my computer, working with AD module.
Other colleagues will access my computer through PSSession to execute it.
However, they cannot import or use the AD Module cmdlets.
"error initializing default drive: 'unable to contact the server. this may be because this server does not exist, it is currently down, or it does not have the active directory web services running"
Attempt to create the AD PSDrive through AD server running ADWS without success, the following error occurs: "unable to contact the server. this may be because this server does not exist, it is currently down, or it does not have the active directory web services running"
Can you please help me with my implementation or give me an alternative approach?
Hi,
im trying to write a script to
1. get-adgroup with specific pattern
2. foreach group in groups get-adgroupmembers.
3. If get-adgroupmembers does not contain "specific group name" then add group to "specific group name"
4. else exit.
#Get all groups with two conditions $Groups = Get-ADGroup -Filter {Name -like "cond1*" -and Name -like "cond2"} | Select-Object SamAccountName foreach ($Group in $Groups) { $Members = Get-ADGroupMember -Identity $Group -Recursive | Select SamAccountName if ("SpecificGroup" -notcontains $Group) { Add-ADGroupMember -Identity $Group -Members "SpecificGroup" } else { Exit } }
Strange im getting error
et-ADGroupMember : Cannot validate argument on parameter 'Identity'. The Identity property on the argument is null or empty.
why $group is null while i can see that $Groups have a value and when i test $Group it also have a value? i even tested .name and it didnt work either.
any suggestions?
Hi folks.
I am new to powershell and I have created a custom Office Theme for use when creating new office documents. It consists of a theme file (*.thmx), a Colors file (*.xml) and a Fonts file (*.xml)
For users to be able to use this theme these files must be located here:
*.thmx file: %APPDATA%\Microsoft\Templates\Document Themes
Colour file: %APPDATA%\Microsoft\Templates\Document Themes\Theme Colors
Font file: %APPDATA%\Microsoft\Templates\Document Themes\Theme Fonts
The files are all stored in the same network folder G:\Office\Theme
I have created the following powershell script, but I wonder if there is a better way to do this. Maybe using Get-ChildItem for the files and storing the *.xml-files in the correct folder under G:\Office\Theme?
$LogBest regards
Trond Kvalo
Hello Everyone,
I have a need to move a user from a child domain to the parent domain. While running the below cmdlet I am getting back an error stating "Server is unwilling to process the request".
Move-ADObject -Server dc01.domain.local:3268 -Identity "distinguished name of user" -TargetPath "distinguished path of OU" -TargetServer dc01.domain.local:3268
Can anyone provide an example of how to use move-ADObject to move a user account from a child domain to parent?
I realize I can use ADMT but I need a way to do this programmatically. Unless ADMT has API to call?
Thanks for any info
Ian...
I am a little lost with this becuase in my text file it only hit's the first computer and not the others. Any feedback would be helpful. here is what I have below
$sessions = get-content ".\desktop\Computers.txt" | % { New-PSSession -ComputerName $_ -ThrottleLimit 60 }I have a list of servernames in a txt file.
I want to run a powershell command against each of these servers.. is there a way to do that?
Thanks,
Mark
Hi!
I have the following command which gives me the patch history information for a server:
wmic qfe list
Is there any way I can pass this through to a SQL Server table?
Thanks,
Zoe
Hi!
Im trying to insert a powershell variable into a SQL table. My SQL table definition is:
CREATE TABLE [dbo].[patch_info]( [Source] [nchar](150) NULL, [Description] [nchar](150) NULL, [HotfixID] [nchar](50) NULL, [InstalledBy] [nchar](150) NULL, [InstalledOn] [datetime] NULL )
My Powershell code is:
$table = Get-wmiobject -class win32_quickfixengineering $table.foreach { $Source = $table.source $Description = $table.description $HotFixID = $table.HotFixID $Installedby = $table.Installedby $InstalledOn = $table.InstalledOn $insertQuery =" Insert Into dbo.patch_info ([Source], [Description], [HotFixID], [InstalledBy], [InstalledOn]) Values ('$Source','$Description', '$HotFixID', '$InstalledBy', '$InstalledOn')" Invoke-Sqlcmd -ServerInstance "Server\Instance" -Query $insertQuery -Database MyDB }
It should insert about 20 rows into SQL, but it doesnt insert anything. There is no error.
Any idea what im doing wrong?
Thanks,
Zoe
Hi All,
I have written the following PnP script to make sites read-Only but the If HasUniqueRoleAssignements statements are not working as should as they are not identifying whether a subsite (not Site Collection) has broken permission inheritance. the script is just defaulting to the last Else code functions. Please help as I have spent days trying to sort this.
Connect-PnPOnline -Url $siteUrl -Credential $Credentials Write-host "Connected to $siteURL" -ForegroundColor Yellow Add-Content C:\TEMP\SiteReadOnlyLogs\$LogName.txt "Connected to $siteURL" $Site = Get-PnPWeb -Includes RoleAssignments If ($Site.IsRootWeb -eq $true) { DDT_AmendSitePermissions DDT_AmendListPermissions Write-host "This is a Site Collection" -ForegroundColor Blue Add-Content C:\TEMP\SiteReadOnlyLogs\$LogName.txt "This is a Site Collection" } ElseIf ( ($Site.HasUniqueRoleAssignments -And $Site.HasUniqueRoleDefinitions) -eq $false) { #$Site.RoleDefinitions.BreakInheritance($true, $true) $Site.BreakRoleInheritance($true,$true) $Site.Update() Write-Host "$siteUrl Inheritance now broken" -ForegroundColor Green Add-Content C:\TEMP\SiteReadOnlyLogs\$LogName.txt "$siteUrl Inheritance now broken" DDT_AmendSitePermissions DDT_AmendListPermissions } Else { Write-Host "$siteUrl Inheritance already broken" -ForegroundColor DarkGreen Add-Content C:\TEMP\SiteReadOnlyLogs\$LogName.txt "$siteUrl Inheritance already broken" DDT_AmendSitePermissions DDT_AmendListPermissions }
Also having the same issue trying to identify if a List within the sites has broken permission inheritance using the statement below, which seemed to wok for the first For Each loop but not subsequent ones. checked variables etc.
ElseIf ( ($Site.HasUniqueRoleAssignments -And $Site.HasUniqueRoleDefinitions) -eq $false)
Thanks in Advance
hey i mange to do the script to find all computers from 6 months ago
$dateOld = (Get-Date).AddDays(-180) Get-ADComputer -Filter {LastLogonDate -lt $dateOld} -Properties *|select Name, DNSHostName, Operatingsystem, LastLogonDate
no i want to add another filter like
{OperatingSystem -Like '*Windows 7 Professional'}
but when i try to combine the the script docent work
I want to find all windows 7 computers with oldest logon date more then 6 monthes